Archive for the ‘Android Tutorials’ Category

Catching Game using AndEngine

January 16th, 2012 by admin | 1 Comment | Filed in Android Game Programming, Android Tutorials

mangoCatch
In this article we will learn how to develop a catching game using
andEngine. There are following steps :

Step :1 Create a project using motodev.

Step :2 Integrate andengine.jar in the library(Please check our previous article if you are facing any problem to integrate it.)

Step :3: Create the MainGame.java activity file and put following code in it :


package com.MangoCatcher;

import java.util.ArrayList;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import java.util.Random;
import org.anddev.andengine.ui.activity.BaseGameActivity;

public class MainGame extends BaseGameActivity implements IOnSceneTouchListener {
	public static MainGame _main;
    public static final int CAMERA_WIDTH = 480;
    public static final int CAMERA_HEIGHT = 800;
    private static Camera _camera;
	private TextureRegion _basketTextureRegion;
	private TextureRegion _mangoTextureRegion;
	private Sprite _basketSprite;
	private ArrayList _mangoesArray = new ArrayList();
	private int _score = 0;

    public Engine onLoadEngine() {
    	_main = this;
    	MainGame._camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
        Engine _engine = new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT,new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),MainGame._camera));
        return _engine;
    }

    /*
     * loading the resources.
     * @see org.anddev.andengine.ui.IGameInterface#onLoadResources()
     */

    public void onLoadResources() {
    	Texture texture = new Texture(256, 128);
    	_basketTextureRegion   = TextureRegionFactory.createFromAsset(texture, this, "gfx/basket.png", 0, 0);
    	_mangoTextureRegion = TextureRegionFactory.createFromAsset(texture, this, "gfx/mango.png", 125, 0);
    	this.mEngine.getTextureManager().loadTexture(texture);
    	this.onLoadSprites();
    }

    /*
     * Loading Sprites of textures
     */
    public void onLoadSprites() {
    	_basketSprite = new Sprite(getScreenCenterX(_basketTextureRegion.getWidth()), CAMERA_HEIGHT - _basketTextureRegion.getHeight(), _basketTextureRegion);
    }

    /*
     * Updating the mangoes positions.
     * Adding mangoes in the scene
     * @see org.anddev.andengine.ui.IGameInterface#onLoadScene()
     */
	@Override
    public Scene onLoadScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());
        final Scene scene = new Scene(1);
        scene.getTopLayer().addEntity(_basketSprite);
        scene.registerUpdateHandler(new IUpdateHandler() {
        	private long lastRaindropAdd = 0;
			@Override
        	public void onUpdate(final float pSecondsElapsed) {
				upDateMangoPoistion(scene);
        		if (System.currentTimeMillis() - lastRaindropAdd  > 3000) {
        			lastRaindropAdd = System.currentTimeMillis();
        			addMangoes(scene);
        		}
            }

			@Override
			public void reset() {

			}
        });

        scene.setOnSceneTouchListener(this);
        return scene;
    }
	/*
     * Updating the mangoes positions.
     */
	private void upDateMangoPoistion(Scene scene){
		int size = _mangoesArray.size();
		for (int i = 0; i < size; i++)
		{
			Sprite raindrop = _mangoesArray.get(i);
			raindrop.setPosition(raindrop.getX(), raindrop.getY() + 5);
			if (raindrop.collidesWith(_basketSprite)) {
				_score++;
				System.out.println("Score: " + _score);
				synchronized(raindrop) {
					size--;
					_mangoesArray.remove(i);
					scene.getTopLayer().removeEntity(raindrop);
				}
			}

			else if (raindrop.getY() > CAMERA_HEIGHT) {
				_score--;
				System.out.println("Score: " + _score);
				synchronized(raindrop) {
					size--;
					_mangoesArray.remove(i);
					scene.getTopLayer().removeEntity(raindrop);
				}
			}
		}
	}

	/*
     * Adding mangoes in the scene
     */
	public void addMangoes(Scene scene){
		 int START = 1;
		 int END = 300;
		 Random random = new Random();
		 int randomInt = showRandomInteger(START, END, random);
		Sprite raindrop = getMango(randomInt, 0);
		_mangoesArray.add(raindrop);
		scene.getTopLayer().addEntity(raindrop);
	}

	/*
     * Getting the random x position for mangoes.
     */

	public int  showRandomInteger(int aStart, int aEnd, Random aRandom){
	    if ( aStart > aEnd ) {
	      throw new IllegalArgumentException("Start cannot exceed End.");
	    }
	    //get the range, casting to long to avoid overflow problems
	    long range = (long)aEnd - (long)aStart + 1;
	    // compute a fraction of the range, 0 <= frac < range
	    long fraction = (long)(range * aRandom.nextDouble());
	    int randomNumber =  (int)(fraction + aStart);
	     return randomNumber;
	  }

	/*
     * Getting the Sprite for mangoes.
     */

	public Sprite getMango(float x, float y) {
		return (new Sprite(x, y, _mangoTextureRegion.clone()));
	}

	/*
	 * (non-Javadoc)
	 * @see org.anddev.andengine.ui.IGameInterface#onLoadComplete()
	 */
	@Override
	public void onLoadComplete() {

	}

	/*
	 * On touch moving the basket
	 * @see org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener#onSceneTouchEvent(org.anddev.andengine.entity.scene.Scene, org.anddev.andengine.input.touch.TouchEvent)
	 */
	@Override
	public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
		this.runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				float touchX = pSceneTouchEvent.getX();
				_basketSprite.setPosition(touchX - _basketSprite.getWidth()/2, _basketSprite.getY());
			}
		});
		return true;
	}
	/*
     * Getting the Screens CenterX.
     */
	public float getScreenCenterX(float width) {
		return (CAMERA_WIDTH / 2) - width / 2;
	}
	/*
     * Getting the Screens CenterY.
     */
	public float getScreenCenterY(float height) {
		return (CAMERA_HEIGHT / 2) - height / 2;
	}
}

Step :4 put two png for Mango and the basket into assets/gfx folder.

Step :5 Run your app.

Attached is the source code of file.
downloadSource

Tags: , , , , , , , , , , , , , , , , ,

Android Game Architecture using AndEngine

January 16th, 2012 by admin | 1 Comment | Filed in Android Game Programming, Android Tutorials

GameArchitecture

In this article we are going to learn how to create a basic architecture of a game. I am using the flow :
1. Splash Screen : which will contain
a) Play Button
b) Quit Button

2. Level Selection Screen :
On touching play button , it will take player to the level
slection screen, where we have to show number of levels ,locked and unlocked levels etc.. In this screen I am showing following buttons
a) Level 1 Button
b) Level locked button
c) Back Button : to swich on previous levels screen
d) Up Button : to swich splash screen
e) Next Button : to swich on nextlevels screen

Use following steps to create the Game architecture using AndEngine :

Step :1 Create a motoDev Project.

Step : 2 Include the AndEngine in the project. Here is example how we import andengine in project.

Srep : 3 Create the GameController.java as the activity class.
put following code there :


package com.thegame;
import java.util.Date;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import com.badlogic.gdx.math.Vector2;

public class GameController extends BaseGameActivity{

/*
* In this class we are going to handle the GameLogic.
* @param LevelController : This class is going to Manage the Levels.
*/
public LevelController _levelManager;
private Camera _camera;
protected PhysicsWorld _physicsWorld;
public Texture _texture;
public Texture _levelBtnTexture;
public TextureRegion _levelBtnTextureRegion;
static GameController _gameController;
public static GameController getInstance(){return _gameController;}

/*
* Here we are defining the texture and its region for various buttons.
* @param _backBtnTexture : Defing BACK button texture.
* @param _backBtnTextureRegion : Defing BACK button texture region.
* @param _upBtnTexture : Defing UP button texture.
* @param _upBtnTextureRegion : Defing UP button texture region.
*/

public Texture _backBtnTexture;
public TextureRegion _backBtnTextureRegion;
public Texture _upBtnTexture;
public TextureRegion _upBtnTextureRegion;
public Texture _nextBtnTexture;
public TextureRegion _nextBtnTextureRegion;
public Texture _navigationDisabledTexure;
public TextureRegion _btnNextDisableRegion;
public TextureRegion _btnBackDisableRegion;

/*
* Here we are defining the texture and its region for various level buttons.
* @param _level1Texture : Defing level 1 button texture.
* @param TextureRegion : Defing level 1 button texture region.
*
*/

public Texture _level1Texture;
public TextureRegion _levelBtnTextureRegion1;
public TextureRegion _levelBtnTextureRegionLocked;

public Texture mLevelSignTextures;
public TextureRegion mLevelCompletedRegion;
public TextureRegion mLevelUnCompletedRegion;

long lDateTime = -1;
int currentPage;

/*
* Here we areLoading the engine.
*
*
*/

@Override
public Engine onLoadEngine() {
currentPage = 0;
_gameController = this;
_levelManager = new LevelController(this);
_levelManager._cameraWidth = 460;
_levelManager._cameraHeight = 320;
_camera = new Camera(0, 0, _levelManager._cameraWidth, _levelManager._cameraHeight);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(_levelManager._cameraWidth, _levelManager._cameraHeight), _camera).setNeedsSound(true));
}

/*
* Here we areLoading the assets.
*
*
*/
@Override
public void onLoadResources() {
loadSplashButtonsTextures();
loadLevelSelectionScreenButtonsTexture();
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mEngine.getTextureManager().loadTextures(this._navigationDisabledTexure, this._splashBtnTexture,this._levelBtnTexture
, this._backBtnTexture, this._upBtnTexture, this._nextBtnTexture, this._level1Texture);

}
/*
* Here we areLoading the assets for Splash Screen.
*
*
*/
public void loadSplashButtonsTextures(){
this._splashBtnTexture = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this._playButtonTextureRegion = TextureRegionFactory.createFromAsset(this._splashBtnTexture, this, "gfx/playbtn.png", 0, 0);
this._quitBtnTextureRegion = TextureRegionFactory.createFromAsset(this._splashBtnTexture, this, "gfx/quitbtn.png", 0, 50);
}
/*
* Here we areLoading the assets for Level Selection Screen.
*
*
*/
public void loadLevelSelectionScreenButtonsTexture(){
loadLevelButton();
loadNavigationLevelSecelectionButtons();
}

/*
* Here we areLoading the assets for level Buttons.
*
*
*/
public void loadLevelButton(){
this._levelBtnTexture  = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
_levelBtnTextureRegion = TextureRegionFactory.createFromAsset(this._levelBtnTexture, this, "gfx/level1_btn.png", 0, 0);
_level1Texture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
_levelBtnTextureRegion1 = TextureRegionFactory.createFromAsset(this._level1Texture, this, "gfx/level1_btn.png", 0, 0);
_levelBtnTextureRegionLocked = TextureRegionFactory.createFromAsset(this._level1Texture, this, "gfx/level_locked.png", 0, 128);
}

/*
* Here we areLoading the assets for navigation  Buttons.
*
*
*/

public void loadNavigationLevelSecelectionButtons(){
_backBtnTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
_backBtnTextureRegion = TextureRegionFactory.createFromAsset(this._backBtnTexture, this, "gfx/back_btn.png", 0, 0);
_upBtnTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
_upBtnTextureRegion = TextureRegionFactory.createFromAsset(this._upBtnTexture, this, "gfx/up_btn.png", 0, 0);
_nextBtnTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
_nextBtnTextureRegion = TextureRegionFactory.createFromAsset(this._nextBtnTexture, this, "gfx/next_btn.png", 0, 0);
_navigationDisabledTexure = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
_btnBackDisableRegion = TextureRegionFactory.createFromAsset(this._navigationDisabledTexure, this, "gfx/back_disable_btn.png", 0, 0);
_btnNextDisableRegion = TextureRegionFactory.createFromAsset(this._navigationDisabledTexure, this, "gfx/next_disable_btn.png", 0, 64);

}
/*
* Here we areLoading the Level on touching level 1 button.
* It is the entry point of your game
*
*/

public Scene newGameLevelScene(int levelId){
Scene scene = new Scene(2);
this._physicsWorld = new FixedStepPhysicsWorld(60, new Vector2(0, 0), false);
_levelManager.loadLevel(levelId);
scene.registerUpdateHandler(this._physicsWorld);
return scene;
}

@Override
public Scene onLoadScene() {
return onLoadSplashScene();
}

@Override
public void onLoadComplete() {
// TODO Auto-generated method stub

}

final int con = 10;	//MENU
protected static final int MENU_PLAY = 0;
protected static final int MENU_QUIT = MENU_PLAY + 1;

private Texture _splashBtnTexture;
protected TextureRegion _playButtonTextureRegion;
protected TextureRegion _quitBtnTextureRegion;

public Scene onLoadSplashScene() {
return createSplashScene();

}

public boolean checkTouchTime(){

if(lDateTime == -1)
{
lDateTime = new Date().getTime();
return true;
}

long lDateCurrentTime = new Date().getTime();
if(lDateCurrentTime - lDateTime > 500)
{
lDateTime = lDateCurrentTime;
return true;
}
return false;
}
/*
* Here we are Createing assets for the quit screen .
*
*
*/
protected Scene createQuitScene() {

Scene scene = new Scene(2);
Sprite _buttonRef = new Sprite(100, 100, 150, 70, this.mMenuOkTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
GameController.getInstance().finish();

return true;
}
};

scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);

_buttonRef = new Sprite(100, 170, 150, 70, this.mMenuBackTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
GameController.getInstance().mEngine.setScene(GameController.getInstance().createSplashScene());
return true;
}
};
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);
return scene;
}

/*
* Here we are Createing assets for the splash screen .
*
*
*/
protected Scene createSplashScene() {
Scene scene = new Scene(2);
addPlayButton(scene);
addQuitButton(scene);
return scene;
}

public void addPlayButton(Scene scene){
Sprite _buttonRef = new Sprite(100, 50, 100, 70, this._playButtonTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
GameController.getInstance().mEngine.setScene(GameController.getInstance().createLevelSubmenu(currentPage));
return true;
}
};
_buttonRef.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);
}

public void addQuitButton(Scene scene){
Sprite _buttonRef = new Sprite(100, 130, 100, 70, this._quitBtnTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
{
GameController.getInstance().finish();
}
return true;
}
};
_buttonRef.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);
}

public void createLevelMenuButtonLayout(Scene scene, boolean backButton){
int height = 50;
int weight = 50;
int x = 200;
int y = 200;
Sprite _buttonRef = new Sprite(x, y, height, weight, _backBtnTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
GameController.getInstance().mEngine.setScene(newGameLevelScene(1));
return true;
}
};
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);
}

public Scene createLevelSubmenu(int id){
Scene scene = new Scene(2);
addMenuLevelItemsPage1(scene);
return scene;
}

private TextureRegion mMenuOkTextureRegion;
private TextureRegion mMenuBackTextureRegion;

protected void onLoadSubMenuResources(){

}

//set up all menu level items
public void addMenuLevelItemsPage1(Scene scene){

int height = 60;
int weight = 60;
int x = 10;
int y = 10;
Sprite _buttonRef;
_buttonRef = new Sprite(x, y, height, weight, _levelBtnTextureRegion1)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
GameController.getInstance().mEngine.setScene(newGameLevelScene(1));
return true;
}
};
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);

x += weight + 10;
addLockedbutton(_buttonRef,scene, x , y,height,weight);
x += weight + 10;
addLockedbutton(_buttonRef,scene, x , y,height,weight);
x += weight + 10;
addLockedbutton(_buttonRef,scene, x , y,height,weight);
y += height + 150;
x = 100;
height = 60;
weight = 60;
addPrevBtton(_buttonRef,scene, x , y,height,weight);
x += weight + 30;
addUpBtton(_buttonRef,scene, x , y,height,weight);
x += weight + 30;
addNextBtton(_buttonRef,scene, x , y,height,weight);

}

public void addLockedbutton(Sprite _buttonRef,Scene scene,int x , int y, int height, int width ){
_buttonRef = new Sprite(x, y, height, width, _levelBtnTextureRegionLocked);
scene.getTopLayer().addEntity(_buttonRef);
}

public void addUpBtton(Sprite _buttonRef,Scene scene,int x , int y, int height, int width ){
_buttonRef = new Sprite(x, y, height, width, _upBtnTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
GameController.getInstance().mEngine.setScene(GameController.getInstance().createSplashScene());
return true;
}
};
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);
}
public void addPrevBtton(Sprite _buttonRef,Scene scene,int x , int y, int height, int width ){
_buttonRef = new Sprite(x, y, height, width, _btnBackDisableRegion);
scene.getTopLayer().addEntity(_buttonRef);

}

public void addNextBtton(Sprite _buttonRef,Scene scene,int x , int y, int height, int width ){

_buttonRef = new Sprite(x, y, height, width, _nextBtnTextureRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(checkTouchTime())
{
currentPage++;
GameController.getInstance().getEngine().setScene(createLevelSubmenu(currentPage));
}
return true;
}
};
scene.registerTouchArea(_buttonRef);
scene.getTopLayer().addEntity(_buttonRef);
}

}

Step 4: Create the LevelController.java class and put following code :

package com.thegame;

import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.input.touch.TouchEvent;

public class LevelController   {
public Scene scene;
private GameController _gameController;
public GameController get_gameController() {
return _gameController;
}
int levelId;
boolean isGameFinished = false;
protected int _cameraWidth;
public int getCameraWidth() {
return _cameraWidth;
}
public int getCameraHeight() {
return _cameraHeight;
}
protected int _cameraHeight;
public LevelController(GameController _gameController) {
levelId = 0;
this._gameController = _gameController;
}
public void setCurrentLevel(int levelId){
this.levelId = levelId;
}

/*
* Here we are defining Level complete image.
* Use this if level is completed.
*/
public void showSignCompleted(){
Shape box = new Sprite(160, 120, 100,100, _gameController.mLevelCompletedRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(GameController.getInstance().checkTouchTime()){
GameController.getInstance().getEngine().setScene(_gameController.createLevelSubmenu(_gameController.currentPage));
}
return true;
}
};
scene.registerTouchArea(box);
scene.getTopLayer().addEntity(box);
}
/*
* Here we are defining Level Uncomplete image.

*/
public void showSignUncompleted(){
Shape box = new Sprite(160, 120, 100, 100, _gameController.mLevelUnCompletedRegion)
{
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
{
if(GameController.getInstance().checkTouchTime())
{
_gameController.getEngine().setScene(_gameController.newGameLevelScene(levelId));
}
return true;
}
};
scene.registerTouchArea(box);
scene.getTopLayer().addEntity(box);
}
public void createBackground(){

}
/*
* Here we are defining Level.
* Use this function to create your level for the game  according to selected level.
* For Example first create the Background etc.
*/
public void loadLevel(int levelId){
isGameFinished = false;
this.setCurrentLevel(levelId);
if(levelId == 1)
loadLevel1();

}
/*
* Here we are defining Level.
* Use this function to create your level for the game .
* For Example first create the Background etc.
*/

public void loadLevel1(){
createBackground();
}

}

Step 5: Run your app . Here is source
downloadSource

Tags: , , , , , , , , , , , , , , , , ,

Android Game using AndEngine

January 12th, 2012 by admin | 1 Comment | Filed in Android Game Programming, Android Tutorials

We will learn how to develop a game using AndEngine which is a openSource, free game engine :) for android.
Step :1. Download the AndEngine from here :

AndEngine.jar

Step :2. Create a new project using motodev.
andEngine
Step :3. Create a new folder ‘lib’ and paste AndEngine.jar file there.
lib_folder

Paste the AndEngine.jar file
inside_lib_folder

Step :4. Go to project properyies and add AndEngine.jar file in the build path.
java build path

Step :5. Open MainActivity.java file and extend it to the BaseActivity

Step :6 You will get an error thrown. Now import the default methods of AndEngine.
extend to the base activity of AndEnine
Step :7. Your Main activity will look like this. These four are the default method of AndEngine

a)onLoadEngine()
a)onLoadResources()
a)onLoadScene()
a)onLoadComplete()

package com.andenginedemo;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.ui.activity.BaseGameActivity;

public class MainActivity  extends BaseGameActivity {

@Override
public Engine onLoadEngine() {
// TODO Auto-generated method stub
return null;
}

@Override
public void onLoadResources() {
// TODO Auto-generated method stub

}

@Override
public Scene onLoadScene() {
// TODO Auto-generated method stub
return null;
}

@Override
public void onLoadComplete() {
// TODO Auto-generated method stub

}
/** Called when the activity is first created. */

}

Step :7. Open the assets folder and create a folder gfx and put the ball.png file there.

Step :8. Now put following code in your MainActivity.java class

package com.andenginedemo;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;

import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;

public class MainActivity  extends BaseGameActivity {

private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;

private Camera _refCamera;
private Texture _ballBitmapTexture;
private TextureRegion _ballTextureRegion;

@Override
public Engine onLoadEngine() {
this._refCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this._refCamera));
}

@Override
public void onLoadResources() {
this._ballBitmapTexture =  new Texture(256,256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this._ballTextureRegion= TextureRegionFactory.createFromAsset(this._ballBitmapTexture, this, "gfx/ball.png", 0, 0); // 64x32
this.mEngine.getTextureManager().loadTexture(this._ballBitmapTexture);
}

@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
Scene scene = new Scene(2);
scene.setBackground(new ColorBackground(0.0000f, 0.0000f, 0.0000f));
/* Calculate the coordinates for the face, so its centered on the camera. */
final int centerX = (CAMERA_WIDTH - this._ballTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this._ballTextureRegion.getHeight()) / 2;

/* Create the face and add it to the scene. */
final Sprite face = new Sprite(centerX, centerY, this._ballTextureRegion);
scene.getTopLayer().addEntity(face);
return scene;
}

@Override
public void onLoadComplete() {

}

}

Step :9. Run your app it will look like this. Enjoy :)
final
downloadSource

Tags: , , , , , , , , , , , , , , , , ,

Box2D Game demo in Android

January 10th, 2012 by admin | 1 Comment | Filed in Android Game Programming, Android Tutorials

Lets see in this tutorial we will learn how to develop an android game with Box2d. There are following steps :

Step :1. Create a project using motodev.
1

Step :2. Create a lib folder inside the project and put jbox2d-2.0.1-full.jar file there.
lib_folder
Step :3. Open the project properties and add the jar file in the library.
import_Jbox
Step :4. Rename the MainActivity.java into Box2dGame.java put the same in AndroidManifest.xml. Now open the class and put following code

package com.physicssample;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;

public class Box2dGame extends Activity
{
    private GLSurfaceView _surfaceView;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        _surfaceView = new ClearGLSurfaceView(this);
        setContentView(_surfaceView);
    }

    @Override
    protected void onPause() {
        super.onPause();
        _surfaceView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        _surfaceView.onResume();
    }

}

Step :5. Now create a ClearGLSurfaceView.java class and put following code inside the class

package com.physicssample;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

public class ClearGLSurfaceView extends GLSurfaceView
{
    ClearRenderer _refRenderer;
    public ClearGLSurfaceView(Context context) {
        super(context);
        _refRenderer = new ClearRenderer(context);
        setRenderer(_refRenderer);
    }

    public boolean onTouchEvent(final MotionEvent event) {
        _refRenderer.setSize(this.getWidth(),this.getHeight());
        queueEvent(new Runnable(){
            public void run() {
              _refRenderer.touchEvent(event.getX(), event.getY(), event.getAction());
            }});
            try {
                   Thread.sleep(20);
             } catch (InterruptedException e) {
                e.printStackTrace();
             }
            return true;
        }
}

Step :5. Now create a ClearRenderer.java class and put following code inside the class

package com.physicssample;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.jbox2d.collision.PolygonShape;
import org.jbox2d.collision.Shape;
import org.jbox2d.collision.ShapeType;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.view.MotionEvent;

public class ClearRenderer implements GLSurfaceView.Renderer
{
    private PhysicsWorld _physicsWorld;
    private ObjectCreater _refBox;
    private Context _context;
    private int _width;
    private int _height;

    public ClearRenderer(Context newContext)
    {
        _context = newContext;
        _refBox = new ObjectCreater(new float[]{-1,-1,0,1,-1,0,1,1,0,-1,1,0}, new float[]{ 0f,1f, 1f,1f, 1f,0f,0f,0f},new short[]{0,1,2,3,0},5);
        _physicsWorld = new PhysicsWorld();
        _physicsWorld.createWorld();
        _physicsWorld.addBox(0f, -25f, 50f, 10f, 0f, false);
    }

public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
            GLU.gluOrtho2D(gl, -12f, 12f, -20f, 20f);
	        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
	        gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
            GL10.GL_REPEAT);
	        gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
            GL10.GL_REPEAT);
	        _refBox.loadTexture(gl, _context, R.drawable.box);
}

public void onSurfaceChanged(GL10 gl, int w, int h)
{
    gl.glViewport(0, 0, w, h);
}

public void onDrawFrame(GL10 gl)
{
    gl.glClearColor(0f, 0, 0.5f, 1.0f);
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
    GL10.GL_REPLACE);
    gl.glColor4f(1f, 1f, 1f, 1f);
    Vec2 vec;
    Body _body = _physicsWorld.getBodyList();
    do
    {
            Shape _shape = _body.getShapeList();
            if (_shape != null)
            {
                    vec = _body.getPosition();
                    float rot = _body.getAngle() * 57f;
                    if (ShapeType.POLYGON_SHAPE == _shape.getType())
                    {
                        Vec2[] _vertexes = ((PolygonShape)_shape).getVertices();
                       _refBox.draw(gl, vec.x, vec.y, 0f, rot, _vertexes[2].x, _vertexes[2].y);
                    }

            }
            _body = _body.getNext();
    }
    while (_body != null);
    _physicsWorld.update();
}

public void touchEvent(float x, float y, int eventCode)
{
    float _worldX = ((x-(this._width/2))*12f)/(this._width/2);
    float _worldY = ((y-(this._height/2))*-20f)/(this._height/2);
    if (eventCode == MotionEvent.ACTION_UP)
    {
        _physicsWorld.addBox(_worldX, _worldY, .98f, .98f, 0f, true);                             

    }
 }

public void setSize(int x, int y)
{
    this._width = x;
    this._height = y;
}
}

Step :6. Now create a PhysicsWorld.java class and put following code inside the class

package com.physicssample;
import org.jbox2d.collision.AABB;
import org.jbox2d.collision.PolygonDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;

public class PhysicsWorld
{
    final private int MAXBOX = 20;
    final private float FRAMERATE = 30f;
    private float _timeStep = (1f / FRAMERATE);
    private int _iterations = 5;
    private int _count = 0;

    private AABB _box2dWorld;
    private World _myWorld;

    public void createWorld()
    {
        _box2dWorld = new AABB();
        _box2dWorld.lowerBound.set(new Vec2(-100f, -100f));
        _box2dWorld.upperBound.set(new Vec2(100f, 100f));

        Vec2 gravity = new Vec2(0f, -10f);
        boolean doSleep = false;
        _myWorld = new World(_box2dWorld, gravity, doSleep);

    }

    public void setGrav(float x, float y)
    {
        _myWorld.setGravity(new Vec2(x,y));
    }

    public void addBox(float x, float y, float xr, float yr, float angle, boolean dynamic)
    {
        if (_count < (MAXBOX-1))
        {
                BodyDef _groundBody;
                _groundBody = new BodyDef();
                _groundBody.position.set(new Vec2(x, y));
                _groundBody.angle = angle;
                Body groundBody = _myWorld.createBody(_groundBody);

                PolygonDef _groundShape;
                _groundShape = new PolygonDef();
                _groundShape.setAsBox(xr, yr);
                _groundShape.density = 1.0f;
                groundBody.createShape(_groundShape);
                if (dynamic)
                {
                        groundBody.setMassFromShapes();
               }
               if (dynamic)
               {
                        _count++;
                }
        }
    }

    public void update()
    {
        _myWorld.step(_timeStep, _iterations);
    }

    public int getCount()
    {
        return _count;
    }

    public Body getBodyList()
    {
        return _myWorld.getBodyList();
    }
}

Step :6. Now create a ObjectCreater.java class and put following code inside the class

package com.physicssample;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

public class ObjectCreater
{
        private FloatBuffer _vertexBuffer;
        private ShortBuffer _indexBuffer;
        private FloatBuffer _texBuffer;
        private int _vertexCount = 0;
        private boolean _hasTexture = false;
        private int[] _texture = new int[1];

        public ObjectCreater(float[] coords, float[] tcoords, short[] icoords, int vertexes)
        {
                this(coords, icoords, vertexes);
                _texBuffer = makeFloatBuffer(tcoords);
        }

        public ObjectCreater(float[] coords, short[] icoords, int vertexes)
        {
            _vertexCount = vertexes;
            _vertexBuffer = makeFloatBuffer(coords);
            _indexBuffer = makeShortBuffer(icoords);
        }

    protected static FloatBuffer makeFloatBuffer(float[] arr) {
        ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer fb = bb.asFloatBuffer();
        fb.put(arr);
        fb.position(0);
        return fb;
    }

    protected static ShortBuffer makeShortBuffer(short[] arr) {
        ByteBuffer bb = ByteBuffer.allocateDirect(arr.length*4);
        bb.order(ByteOrder.nativeOrder());
        ShortBuffer ib = bb.asShortBuffer();
        ib.put(arr);
        ib.position(0);
        return ib;
    }

        public void loadTexture(GL10 gl, Context mContext, int mTex) {
                _hasTexture = true;
		        gl.glGenTextures(1, _texture, 0);
		        gl.glBindTexture(GL10.GL_TEXTURE_2D, _texture[0]);
		        Bitmap bitmap;
		        bitmap = BitmapFactory.decodeResource(mContext.getResources(), mTex);
		        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
		        bitmap.recycle();
                gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR );
                gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR );
        }

       public void draw(GL10 gl) {
                if (_hasTexture) {
                gl.glEnable(GL10.GL_TEXTURE_2D);
                gl.glBindTexture(GL10.GL_TEXTURE_2D, _texture[0]);
                    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, _texBuffer);
                } else {
                    gl.glDisable(GL10.GL_TEXTURE_2D);
                }
	            gl.glFrontFace(GL10.GL_CCW);
	            gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _vertexBuffer);
	            gl.glDrawElements(GL10.GL_TRIANGLE_FAN, _vertexCount, GL10.GL_UNSIGNED_SHORT, _indexBuffer);
                gl.glDisable(GL10.GL_TEXTURE_2D);
        }

        public void draw(GL10 gl, float x, float y, float z, float rot, float scale) {
                this.draw(gl, x, y, z, rot, scale, scale);
        }

        public void draw(GL10 gl, float x, float y, float z, float rot, float scaleX, float scaleY) {
                gl.glPushMatrix();
                gl.glTranslatef(x, y, z);
                gl.glRotatef(rot, 0f, 0f, 1f);
                gl.glScalef(scaleX, scaleY, 1f);
                this.draw(gl);
                gl.glPopMatrix();
        }

}

Step :6. Run your app it will look like this . If you have any question or need more clarification please write on forum.dremsus.com.
final

Tags: , , , , , , , , , , , , , , , , , , , ,

Handle Collision detection with Sprites

January 6th, 2012 by admin | 3 Comments | Filed in Android Game Programming, Android Tutorials

In this article we are going to learn how to add multiple sprits and handle their Collision. Lets start with following steps :

Step 1: Create a new MotoDev project.
MultipleSprite_Android

Step 2: Create sprite sheet animation for three character’s walk cycle.

boy1

Step 3: Put them in res/drawable folder.

Step 4: Open MainActivity.java class and add following code :

package com.multiplesp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

	@Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new GameController(this));

    }

}

Step 5: Create a new class GameController.java and put following code inside it

package com.multiplesp;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;

public class GameController extends SurfaceView {

    private SurfaceHolder _surfaceHolder;
    private GameThread _gameThread;
    private List Character = new ArrayList();
    private long lastClick;
    public GameController(Context context) {

          super(context);
          _gameThread = new GameThread(this);
          _surfaceHolder = getHolder();
          _surfaceHolder.addCallback(new SurfaceHolder.Callback() {
          @Override
           public void surfaceDestroyed(SurfaceHolder _surfaceHolder) {
                  boolean retry = true;
                  _gameThread.setRunning(false);
                   while (retry) {
                      try {
                    	  _gameThread.join();
                   retry = false;
                   } catch (InterruptedException e) {
                 }
                 }
           }
          @Override
           public void surfaceCreated(SurfaceHolder _surfaceHolder) {
                        createSprites();
                        _gameThread.setRunning(true);
                        _gameThread.start();
            }
            @Override
            public void surfaceChanged(SurfaceHolder _surfaceHolder, int format,
                      int width, int height) {
             }
          });
    }

    private void createSprites() {
    	Character.add(createSprite(R.drawable.boy1));
    	Character.add(createSprite(R.drawable.girl1));
    	Character.add(createSprite(R.drawable.girl2));

    }   

    private Character createSprite(int resouce) {
          Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
          return new Character(this,bmp);
    }

    @Override
    protected void onDraw(Canvas canvas) {
          canvas.drawColor(Color.BLACK);
          for (Character sprite : Character) {
                 sprite.onDraw(canvas);
          }
    }
    @Override

    public boolean onTouchEvent(MotionEvent event) {
          if (System.currentTimeMillis() - lastClick > 500) {
                 lastClick = System.currentTimeMillis();
                 synchronized (getHolder()) {
                     for (int i = Character.size() - 1; i >= 0; i--) {
                    	 Character character = Character.get(i);
                         if (character.isCollition(event.getX(), event.getY())) {
                        	 Character.remove(character);
                               break;
                         }
                     }
                 }
          }

          return true;
    }

}

Step 7: Create a GameThread Class and put following code inside :

package com.multiplesp;

import android.graphics.Canvas;

public class GameThread extends Thread {
       private GameController _gameController;
       private boolean _isRunning = false;
       static final long FPS = 10;

       public GameThread(GameController _gameController) {
             this._gameController = _gameController;
       }

       public void setRunning(boolean run) {
             _isRunning = run;
       }

       @Override

       public void run() {
             long _trackFPS = 1000 / FPS;
             long _startCounter;
             long _sleepTime;
             while (_isRunning) {
                    Canvas _canvas = null;
                    _startCounter = System.currentTimeMillis();
                    try {
                    	_canvas = _gameController.getHolder().lockCanvas();
                        synchronized (_gameController.getHolder()) {
                        _gameController.onDraw(_canvas);
                      }

                    } finally {
                           if (_canvas != null) {
                        	   _gameController.getHolder().unlockCanvasAndPost(_canvas);
                           }
                    }
                    _sleepTime = _trackFPS - (System.currentTimeMillis() - _startCounter);
                    try {
                           if (_sleepTime > 0)
                                  sleep(_sleepTime);
                           else
                                  sleep(10);
                    } catch (Exception e) {}

             }

       }

}

Step 8:Create a Character.java class for your sprites. Put following code inside that:

package com.multiplesp;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect; 

public class Character {
       int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
       private static final int CHAR_ROWS = 4;
       private static final int CHAR_COLUMNS = 3;
       private static final int MAX_SPEED = 5;
       private GameController GameController;
       private Bitmap _characterbmp;
       private int _xPos = 0;
       private int _yPos = 0;
       private int _xVelocity;
       private int _yVelocity;
       private int _currentFrame = 0;
       private int _width;
       private int _height; 

       public Character(GameController GameController, Bitmap _characterbmp) {
             this._width = _characterbmp.getWidth() / CHAR_COLUMNS;
             this._height = _characterbmp.getHeight() / CHAR_ROWS;
             this.GameController = GameController;
             this._characterbmp = _characterbmp;
             Random _randomValue = new Random();
             _xPos = _randomValue.nextInt(GameController.getWidth() - _width);
             _yPos = _randomValue.nextInt(GameController.getHeight() - _height);
             _xVelocity = _randomValue.nextInt(MAX_SPEED * 2) - MAX_SPEED;
             _yVelocity = _randomValue.nextInt(MAX_SPEED * 2) - MAX_SPEED;
       }

       private void update() {
             if (_xPos >= GameController.getWidth() - _width - _xVelocity || _xPos + _xVelocity <= 0) {
                    _xVelocity = -_xVelocity;
             }
             _xPos = _xPos + _xVelocity;
             if (_yPos >= GameController.getHeight() - _height - _yVelocity || _yPos + _yVelocity <= 0) {
                    _yVelocity = -_yVelocity;
             }
             _yPos = _yPos + _yVelocity;
             _currentFrame = ++_currentFrame % CHAR_COLUMNS;
       }

       public void onDraw(Canvas canvas) {
             update();
             int orgX = _currentFrame * _width;
             int orgY = getAnimationRow() * _height;
             Rect src = new Rect(orgX, orgY, orgX + _width, orgY + _height);
             Rect dst = new Rect(_xPos, _yPos, _xPos + _width, _yPos + _height);
             canvas.drawBitmap(_characterbmp, src, dst, null);
       }

       private int getAnimationRow() {
             double dirDouble = (Math.atan2(_xVelocity, _yVelocity) / (Math.PI / 2) + 2);
             int direction = (int) Math.round(dirDouble) % CHAR_ROWS;
             return DIRECTION_TO_ANIMATION_MAP[direction];
       }
       public boolean isCollition(float x2, float y2) {
           return x2 > _xPos && x2 < _xPos + _width && y2 > _yPos && y2 < _yPos + _height;
     }

}

Step 9: Run your application . It should look like this :
final

Tags: , , , , , , , , , , , , , , , , , , , , , , , ,

Handle Multiple Character and their Movement

January 5th, 2012 by admin | 15 Comments | Filed in Android Game Programming, Android Tutorials

In this article we are going to learn how to add multiple sprits and handle their movement. Lets start with following steps :

Step 1: Create a new MotoDev project.
MultipleSprite_Android

Step 2: Create sprite sheet animation for three character’s walk cycle.

boy1

Step 3: Put them in res/drawable folder.

Step 4: Open MainActivity.java class and add following code :

package com.multiplesp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class MainActivity extends Activity {

	@Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new GameController(this));

    }

}

Step 5: Create a new class GameController.java and put following code inside it


package com.multiplesp;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;

public class GameController extends SurfaceView {

    private SurfaceHolder _surfaceHolder;
    private GameThread _gameThread;
    private List Character = new ArrayList();
    public GameController(Context context) {

          super(context);
          _gameThread = new GameThread(this);
          _surfaceHolder = getHolder();
          _surfaceHolder.addCallback(new SurfaceHolder.Callback() {
          @Override
           public void surfaceDestroyed(SurfaceHolder _surfaceHolder) {
                  boolean retry = true;
                  _gameThread.setRunning(false);
                   while (retry) {
                      try {
                    	  _gameThread.join();
                   retry = false;
                   } catch (InterruptedException e) {
                 }
                 }
           }
          @Override
           public void surfaceCreated(SurfaceHolder _surfaceHolder) {
                        createSprites();
                        _gameThread.setRunning(true);
                        _gameThread.start();
            }
            @Override
            public void surfaceChanged(SurfaceHolder _surfaceHolder, int format,
                      int width, int height) {
             }
          });
    }

    private void createSprites() {
    	Character.add(createSprite(R.drawable.boy1));
    	Character.add(createSprite(R.drawable.girl1));
    	Character.add(createSprite(R.drawable.girl2));

    }   

    private Character createSprite(int resouce) {
          Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
          return new Character(this,bmp);
    }

    @Override
    protected void onDraw(Canvas canvas) {
          canvas.drawColor(Color.BLACK);
          for (Character sprite : Character) {
                 sprite.onDraw(canvas);
          }
    }

}

Step 7: Create a GameThread Class and put following code inside :

package com.multiplesp;

import android.graphics.Canvas;

public class GameThread extends Thread {
       private GameController _gameController;
       private boolean _isRunning = false;     

       public GameThread(GameController _gameController) {
             this._gameController = _gameController;
       }

       public void setRunning(boolean run) {
             _isRunning = run;
       }

       @Override
       public void run() {
          while (_isRunning) {
                  Canvas _canvas = null;
                    try {
                    	_canvas = _gameController.getHolder().lockCanvas();
                           synchronized (_gameController.getHolder()) {
                                  _gameController.onDraw(_canvas);
                           }

                    } finally {
                           if (_canvas != null) {
                                  _gameController.getHolder().unlockCanvasAndPost(_canvas);
                           }
                    }
             }
       }

}

Step 8:Create a Character.java class for your sprites. Put following code inside that:

package com.multiplesp;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect; 

public class Character {
       int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
       private static final int CHAR_ROWS = 4;
       private static final int CHAR_COLUMNS = 3;
       private static final int MAX_SPEED = 5;
       private GameController GameController;
       private Bitmap _characterbmp;
       private int _xPos = 0;
       private int _yPos = 0;
       private int _xVelocity;
       private int _yVelocity;
       private int _currentFrame = 0;
       private int _width;
       private int _height; 

       public Character(GameController GameController, Bitmap _characterbmp) {
             this._width = _characterbmp.getWidth() / CHAR_COLUMNS;
             this._height = _characterbmp.getHeight() / CHAR_ROWS;
             this.GameController = GameController;
             this._characterbmp = _characterbmp;
             Random _randomValue = new Random();
             _xPos = _randomValue.nextInt(GameController.getWidth() - _width);
             _yPos = _randomValue.nextInt(GameController.getHeight() - _height);
             _xVelocity = _randomValue.nextInt(MAX_SPEED * 2) - MAX_SPEED;
             _yVelocity = _randomValue.nextInt(MAX_SPEED * 2) - MAX_SPEED;
       }

       private void update() {
             if (_xPos >= GameController.getWidth() - _width - _xVelocity || _xPos + _xVelocity <= 0) {
                    _xVelocity = -_xVelocity;
             }
             _xPos = _xPos + _xVelocity;
             if (_yPos >= GameController.getHeight() - _height - _yVelocity || _yPos + _yVelocity <= 0) {
                    _yVelocity = -_yVelocity;
             }
             _yPos = _yPos + _yVelocity;
             _currentFrame = ++_currentFrame % CHAR_COLUMNS;
       }

       public void onDraw(Canvas canvas) {
             update();
             int orgX = _currentFrame * _width;
             int orgY = getAnimationRow() * _height;
             Rect src = new Rect(orgX, orgY, orgX + _width, orgY + _height);
             Rect dst = new Rect(_xPos, _yPos, _xPos + _width, _yPos + _height);
             canvas.drawBitmap(_characterbmp, src, dst, null);
       } 

       private int getAnimationRow() {
             double dirDouble = (Math.atan2(_xVelocity, _yVelocity) / (Math.PI / 2) + 2);
             int direction = (int) Math.round(dirDouble) % CHAR_ROWS;
             return DIRECTION_TO_ANIMATION_MAP[direction];
       }

}

Step 9: Run your application . It should look like this :
output

Tags: , , , , , , , , , , , , , , , , , , , , , , , ,

Coordinate Movement for a Ball

January 2nd, 2012 by admin | 2 Comments | Filed in Android Game Programming, Android Tutorials

Step 1 : Create a new project using Motodev Studio.
1
Step 2: Put an image of ball named “ball_1.png” into res/drwable Folder.

Step 3: Open you MainActivity.java and put following code :

package com.movement;

import android.app.Activity;

import android.os.Bundle;

import android.view.Window;

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(new GameController(this));

}

@Override

protected void onDestroy() {
 super.onDestroy();

}

@Override

protected void onStop() {
super.onStop();

}

}

Step 3: Create a class Ball.java and put following code :


 package com.movement;

 import android.graphics.Bitmap;

import android.graphics.Canvas;

public class Ball {

  private Bitmap bitmap;

  private int x;
  private int y;
  private SpeedManager speed;	

  public Ball(Bitmap bitmap, int x, int y) {

  this.bitmap = bitmap;

  this.x = x;

  this.y = y;

  this.speed = new SpeedManager();

  }

  public Bitmap getBitmap() {

	return bitmap;

  }

  public void setBitmap(Bitmap bitmap) {

  this.bitmap = bitmap;

  }

  public int getX() {

  return x;

  }

  public void setX(int x) {

  this.x = x;

  }

 public SpeedManager getSpeed() {

 return speed;

 }

 public void setSpeed(SpeedManager speed) {

 this.speed = speed;

 }

 public void draw(Canvas canvas) {

 canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2), y - (bitmap.getHeight() / 2), null);

 }

 public void update() {	

  x += (speed.getvelocity() * speed.getxDirection());
 }

}

Step 4: Create a class GameController.java and put following code :

package com.movement;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameController extends SurfaceView implements
		SurfaceHolder.Callback {
	private GameThread thread;
	private Ball ballInstance;

	public GameController(Context context) {
		super(context);
		getHolder().addCallback(this);
		ballInstance = new Ball(BitmapFactory.decodeResource(getResources(), R.drawable.ball_1), 80, 80);
		thread = new GameThread(getHolder(), this);
		setFocusable(true);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {

			}
		}

	}	

	public void render(Canvas canvas) {
		canvas.drawColor(Color.BLACK);
		ballInstance.draw(canvas);
	}

	public void update() {
		if (ballInstance.getSpeed().getxDirection() == SpeedManager.DIRECTION_RIGHT
				&& ballInstance.getX() + ballInstance.getBitmap().getWidth() / 2 >= getWidth()) {
			ballInstance.getSpeed().toggleXDirection();
		}

		if (ballInstance.getSpeed().getxDirection() == SpeedManager.DIRECTION_LEFT
				&& ballInstance.getX() - ballInstance.getBitmap().getWidth() / 2 <= 0) {
			ballInstance.getSpeed().toggleXDirection();
		}

		ballInstance.update();
	}

}

Step 5: Create a thread GameThread.java and put following code :

package com.movement;

import android.graphics.Canvas;
import android.view.SurfaceHolder;

public class GameThread extends Thread {	

	private SurfaceHolder surfaceHolder;
	private GameController gameController;
	private boolean running;
	public void setRunning(boolean running) {
		this.running = running;
	}

	public GameThread(SurfaceHolder surfaceHolder, GameController gameController) {
		super();
		this.surfaceHolder = surfaceHolder;
		this.gameController = gameController;
	}

	@Override
	public void run() {
		Canvas canvas;
		while (running) {
			canvas = null;
			try {
				canvas = this.surfaceHolder.lockCanvas();
				synchronized (surfaceHolder) {
					this.gameController.update();
					this.gameController.render(canvas);
				}
			} finally {
				if (canvas != null) {
					surfaceHolder.unlockCanvasAndPost(canvas);
				}
			}
		}
	}

}

Step 6: Create a thread SpeedManager.java and put following code :

package com.movement;

public class SpeedManager {

	public static final int DIRECTION_RIGHT	= 1;
	public static final int DIRECTION_LEFT	= -1;

	private float velocity = 10;
	private int xDirection = DIRECTION_RIGHT;

	public SpeedManager() {
		this.velocity = 1;

	}

	public SpeedManager(float velocity, float yv) {
		this.velocity = velocity;

	}

	public float getvelocity() {
		return velocity;
	}
	public void setvelocity(float velocity) {
		this.velocity = velocity;
	}	

	public int getxDirection() {
		return xDirection;
	}
	public void setxDirection(int xDirection) {
		this.xDirection = xDirection;
	}	

	public void toggleXDirection() {
		xDirection = xDirection * -1;
	}

}

Step 7:Run your application It will look like this :
2

Tags: , , , , , , , , , , , , , , , , , , , , , ,

Blinking Santa Handling alpha feature

December 16th, 2011 by admin | No Comments | Filed in Android Game Programming, Android Tutorials

In this article we are going to learn how to make an blinking image on touch or click.
There are following steps we need to follow to make Blinking Santa.

Step 1: Create a Project using Motodev. The options will look like this.
1

Step 2: in your res/drwable folder put the image santa.png

Step 3. Open the layout/Main.xml and put following codes




    

Step 4. Open the MainActivity.java and put following codes


package com.blinkingsanta;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.Animation;

import android.view.animation.Animation.AnimationListener;

import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener, AnimationListener {

	private ImageView _santaImage;

   @Override

   public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);        

       _santaImage = (ImageView) findViewById(R.id.image);

       _santaImage.setOnClickListener(this);

    }

  @Override

  public void onClick(View view) {

     if (view.getId() == R.id.image) {

	Animation animation;

        if (_santaImage.getVisibility() == View.VISIBLE) {

	animation = new VisibilityClass(3, true);
	} 

        else
         {

          animation = new VisibilityClass(3, false);				

         }

        animation.setDuration(1000L);

	animation.setAnimationListener(this);
       _santaImage.startAnimation(animation);

	}

    }

  @Override

  public void onAnimationEnd(Animation animation) {

  _santaImage.setVisibility(View.VISIBLE);

  }

  @Override

   public void onAnimationRepeat(Animation animation) {

    }

  @Override

  public void onAnimationStart(Animation animation) {

  }

}

Step 5. Create a new class VisibilityClass.java and put following codes


package com.blinkingsanta;

import android.util.FloatMath;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class VisibilityClass extends Animation {
	private int _totalNumber;
	private boolean _isAnimFinished;

	public VisibilityClass(int _totalNumber, boolean _isAnimFinished) {
		this._totalNumber = _totalNumber;
		this._isAnimFinished = _isAnimFinished;
	}

	@Override
	protected void applyTransformation(float _interpolatedTime, Transformation _trans) {
		float period = _interpolatedTime * _totalNumber * 4.12f + (_isAnimFinished ? 4.12f / 2 : 0);
		_trans.setAlpha(Math.abs(FloatMath.cos(period)));
	}

}

Step 6. Run the app and Click on Santa . It should look like this :)

2

Tags: , , , , , , , , , , , , ,

Handling animation in Android Game Programming

December 13th, 2011 by admin | 1 Comment | Filed in Android Game Programming, Android Tutorials

In this article we are going to learn how to handle the animations for a game in Android programming.
We are going to show an animation of duck and its creation on touch event. So lets begin it wih steps :

Step :1 Create a motodev Project .
1

Step :2 Now put your animation sprite(png) file into res/drawable folder.Your png will look like this
duck

Step :3 Open your Layout/Main.xml file and put following code there :




    
 

Step :4 Open your values/String.xml and put following code inside that



    AnimatedDuck
 

Step :5 Your MainActivity class will look like this :


package com.annimatedspriteapp;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);   

    }

}

Step :6 Now create a Class for the Sprite . Here I am creating the class named ‘DuckSprite’.
and adding following codes :


package com.annimatedspriteapp;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class DuckSprite {
	private Bitmap _duckAnim;
	private int _xPos;
	private int _yPos;
	private Rect _duckRect;
	private int _fps;
	private int _frameCount;
	private int _currentFrame;
	private long _frameTimer;
	private int _duckHeight;
	private int _duckWidth;
	private boolean _loop;
	public boolean dispose;

	public DuckSprite() {
		_duckRect = new Rect(0, 0, 0, 0);
		_frameTimer = 0;
		_currentFrame = 0;
		_xPos = 80;
		_yPos = 200;
		dispose = false;
	}

	public void Initialize(Bitmap __bitmap, int __height, int __width, int __fps, int __frameCount, boolean __loop) {
		this._duckAnim = __bitmap;
		this._duckHeight = __height;
		this._duckWidth = __width;
		this._duckRect.top = 0;
		this._duckRect.bottom = _duckHeight;
		this._duckRect.left = 0;
		this._duckRect.right = _duckWidth;
		this._fps = 1000 / __fps;
		this._frameCount = __frameCount;
		this._loop = __loop;
	}

	public int getXPos() {
		return _xPos;
	}

	public int getYPos() {
		return _yPos;
	}

	public void setXPos(int value) {
		_xPos = value - (_duckWidth/2);
	}

	public void setYPos(int value) {
		_yPos = value - (_duckHeight/2);
	}

	public void Update(long _totalTime) {
		if( _totalTime > _frameTimer + _fps) {
			_frameTimer = _totalTime;
			_currentFrame += 1;

			if( _currentFrame >= _frameCount ) {
				_currentFrame = 0;

				if(!_loop)
					dispose = true;			

			}

			_duckRect.left = _currentFrame * _duckWidth;
			_duckRect.right = _duckRect.left + _duckWidth;
		}
	}

	public void draw(Canvas canvas) {
		Rect dest = new Rect(getXPos(), getYPos(), getXPos() + _duckWidth,
										getYPos() + _duckHeight);
		canvas.drawBitmap(_duckAnim, _duckRect, dest, null);
	}
}

Step :7 Now I am going to create the View Class. Here I named it DuckView


package com.annimatedspriteapp;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;

import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

class DuckView extends SurfaceView implements SurfaceHolder.Callback {
    class AnimationThread extends Thread {
        private Bitmap _duck;
        private ArrayList _mSpritesArray;
        private ArrayList _mSpritesArraytoRemove;        

        private boolean _isRunning = false;
        private SurfaceHolder _mSurfaceHolder;
        private Resources _res;

        public AnimationThread(SurfaceHolder surfaceHolder, Context context, Handler handler) {

            _mSurfaceHolder = surfaceHolder;
            _res = context.getResources();
            _mSpritesArray = new ArrayList();
            _mSpritesArraytoRemove = new ArrayList();           

        }

        @Override
        public void run() {
            while (_isRunning) {
                Canvas _mcanvas = null;
                try {
                	_mcanvas = _mSurfaceHolder.lockCanvas(null);
                    synchronized (_mSurfaceHolder) {
                       	updateAnimation();
                        doDraw(_mcanvas);
                    }
                } catch(Exception e){

                }finally {

                    if (_mcanvas != null) {
                        _mSurfaceHolder.unlockCanvasAndPost(_mcanvas);
                    }
                }
            }
        }

        private void doDraw(Canvas canvas) {
        	canvas.drawColor(Color.BLACK);
        	for( DuckSprite _anDuck : _mSpritesArray){
        		_anDuck.draw(canvas);
        	}
        	canvas.restore();
        }

        private void updateAnimation() {
            long _currentTime = System.currentTimeMillis();
            synchronized(_mSpritesArray){
	            for( DuckSprite _anDuck : _mSpritesArray){
	            	_anDuck.Update(_currentTime);
	            	if(_anDuck.dispose)
	            		_mSpritesArraytoRemove.add(_anDuck);
	            }
            }

            synchronized(_mSpritesArraytoRemove){
	            _mSpritesArray.removeAll(_mSpritesArraytoRemove);
	            _mSpritesArraytoRemove.clear();
            }            

        }

        public void doTouch(MotionEvent event){
        	int action = event.getAction();
            float x = event.getX();
            float y = event.getY();
            switch(action){
            case MotionEvent.ACTION_DOWN:
            		DuckSprite _anDuck = new DuckSprite();
            		if(_duck == null)
            			_duck = BitmapFactory.decodeStream(_res.openRawResource(R.drawable.duck));
            		_anDuck.Initialize(_duck, 100, 100, 35,28, true);
            		_anDuck.setXPos((int)x);
            		_anDuck.setYPos((int)y);
            		synchronized(_mSpritesArray){
            			_mSpritesArray.add(_anDuck);
            		}
            	break;
            }
        }     

        public void setRunning(boolean _flag) {
            _isRunning = _flag;
        }      

        public void setSurfaceSize(int width, int height) {
            synchronized (_mSurfaceHolder) {
            }
        }

    }

    private AnimationThread thread;

    public DuckView(Context context, AttributeSet attrs) {
        super(context, attrs);
        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
        thread = new AnimationThread(holder, context, new Handler() {
        });

        setFocusable(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
    	thread.doTouch(event);
    	return super.onTouchEvent(event);
    }

    public AnimationThread getThread() {
        return thread;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        thread.setSurfaceSize(width, height);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        thread.setRunning(true);
        thread.start();
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        thread.setRunning(false);
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }
}

Step :8 Run your application It will look like this on touch even.
Most of function, varible names are self explanitory . If still you are getting any problem to understand it
write me in our forum section.
2

Tags: , , ,

How to create a Timer for the Bomb in Android

December 2nd, 2011 by admin | 1 Comment | Filed in Android Game Programming, Android Tutorials

Basically we are going to get an idea abot using timer for a bomb game. In this article I have
used just a simple piece of displaying text for the timer. later on we will use this widely in our
complete game.

In this app we are going to learn :
1.How to create a GameLoop.
2.How to use surfaceView.
3.How to display the text and images.
4.How to implementing two classes in same java file.

Step 1: Lets create a new motodev project :
1

Step 2: In your res/drawble folder put bomb.png file.
Step 3: in your res/layout/main.xml put following code :

		
			

				

			
        

Step 4: In the MainActivity.java put following code :

		package com.bombtimer;

			import android.app.Activity;
			import android.os.Bundle;

			public class MainActivity extends Activity {
				/** Called when the activity is first created. */
				@Override
				public void onCreate(Bundle savedInstanceState) {
					super.onCreate(savedInstanceState);
					setContentView(R.layout.main);
				}
			}
		

Step 5: Create a GameLoop.java class and put following code :

		package com.bombtimer;

			import android.content.Context;
			import android.graphics.BitmapFactory;
			import android.graphics.Canvas;
			import android.graphics.Color;
			import android.graphics.Paint;
			import android.util.AttributeSet;
			import android.view.SurfaceHolder;
			import android.view.SurfaceView;

			class GameLoop extends SurfaceView implements SurfaceHolder.Callback {
				class CounterThread extends Thread {
					private boolean isRunning;
					private int counter = 1000;
					private SurfaceHolder refSurfaceHolder;
					private Paint textPaint;

					public CounterThread(SurfaceHolder surfaceHolder) {
						refSurfaceHolder = surfaceHolder;
						textPaint = new Paint();
						textPaint.setARGB(255,255,255,255);
						textPaint.setTextSize(32);
					}

					@Override
					public void run() {
						while (isRunning) {
							Canvas c = null;
							try {
								c = refSurfaceHolder.lockCanvas(null);
								synchronized (refSurfaceHolder) {
									updateTimer();
									doDraw(c);
								}
							}finally {
								if (c != null) {
									refSurfaceHolder.unlockCanvasAndPost(c);
								}
							}
						}
					}

					private void updateTimer() {
						counter -= 1;
					}

					private void doDraw(Canvas canvas) {
						canvas.drawColor(Color.RED);
						bombInstance.draw(canvas);
						canvas.drawText(counter +" : Left Time ", getWidth() / 2, getHeight() / 2, textPaint);
						canvas.restore();
					}        

					public void setRunning(boolean b) {
						isRunning = b;
					}      

				}

				private CounterThread thread;
				private Bomb bombInstance;

				public GameLoop(Context context, AttributeSet attrs) {
					super(context, attrs);
					bombInstance = new Bomb(BitmapFactory.decodeResource(getResources(), R.drawable.bomb), 300, 300);
					SurfaceHolder holder = getHolder();
					holder.addCallback(this);
					thread = new CounterThread(holder);
				}

				public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
					}

				public void surfaceCreated(SurfaceHolder holder) {
					thread.setRunning(true);
					thread.start();
				}

				public void surfaceDestroyed(SurfaceHolder holder) {
					boolean retry = true;
					thread.setRunning(false);
					while (retry) {
						try {
							thread.join();
							retry = false;
						} catch (InterruptedException e) {
						}
					}
				}
			}
          

Step 7: Create a Bomb.java class and put following code :

		  package com.bombtimer;

			  import android.graphics.Bitmap;
			  import android.graphics.Canvas;

			  public class Bomb {

				  private Bitmap bitmap;
				  private int x;
				  private int y;
				  private boolean touched;

				  public Bomb(Bitmap bitmap, int x, int y) {
					  this.bitmap = bitmap;
					  this.x = x;
					  this.y = y;
				  }

				  public Bitmap getBitmap() {
					  return bitmap;
				  }
				  public void setBitmap(Bitmap bitmap) {
					  this.bitmap = bitmap;
				  }
				  public int getX() {
					  return x;
				  }
				  public void setX(int x) {
					  this.x = x;
				  }
				  public int getY() {
					  return y;
				  }
				  public void setY(int y) {
					  this.y = y;
				  }
				  public boolean isTouched() {
					  return touched;
				  }

				  public void setTouched(boolean touched) {
					  this.touched = touched;
				  }
				  public void draw(Canvas canvas) {
					  canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2), y - (bitmap.getHeight() / 2), null);
				  }

			  }
            

Step 8: Run your app it will look like this :

2

Tags: , , , , ,