Sabtu, 07 September 2013

Create a Simple Android Game with AndEngine

How to Create a Simple Android Game with AndEngine

 

Learn how to make a Tower of Hanoi game on Android!
Learn how to make a Tower of Hanoi game on Android!

In this tutorial, you’re going to get hands-on experience making a simple game on Android using AndEngine, a popular and easy to use game framework.
There are many frameworks you can use to make games on Android – the most popular being libGDX, AndEngine and Cocos2D-X. Each engine has its pros and cons.
Cocos2D-X (which we previously covered in a two-part series here and here) is great for making cross-platform games, but it does bring along a bit of extra complexity.
What if you just want to get a simple game working on Android the quickest and easiest way? This is where AndEngine comes in handy! Its API is very easy to use and it takes hardly any time to learn the ins and outs of the engine.
You’ll put AndEngine to work creating a version of the famous mathematical puzzle the Tower of Hanoi. Before you begin, make sure you’ve read my previous two tutorials on Getting Started with Android (here and here), or have some Android development experience under your belt.
Keep reading to get started with AndEngine!

All About the AndEngines

AndEngine logo
Which do you like better, this or the Cocos2D logo?
First, here’s a brief overview of AndEngine, including what I like and dislike about it.
AndEngine is currently available in two flavors: GLES1 and GLES2. As you might have gathered from the name, the GLES1 version supports OpenGL ES 1.x. Almost 99% of Android devices can run a game built using this version.
GLES2, as you might guess, supports OpenGL ES 2.0. This branch is actively being worked on, and nearly 93% of current Android devices can run a game that’s been made with this branch.
AndEngine Pros:
  • It has a complete 2-D scene graph, with a very easy-to-use API.
  • It works really well with the Android activity lifecycle.
  • It has a number of extensions that can be added as plugins.
  • It’s free :]
AndEngine Cons:
  • The biggest problem I’ve faced while using AndEngine is that the API is undocumented. This can increase the development time, as you sometimes need to go through the engine source code to figure things out. Don’t worry though – I’ve got you covered in this tutorial! :]

Getting Started

Now that you know a bit more about AndEngine, it’s time to download the source code and set up the environment.
Note: Since AndEngine is hosted on GitHub, you could always clone the git repository for AndEngine to get the source code for the project. However, this requires that you have git installed on your machine and that you are able to work on the command line.
Open up your browser and go to the AndEngine github page. You should see a link on the page to download the repository as a ZIP file. Use that to download a copy of the AndEngine project. Or, you should be able to use this link to download the file directly.
Extract the downloaded ZIP file to a convenient location on your hard drive.
Now that you’ve got the source code for the game engine, if you want, you can also download the code for additional AndEngine extensions. In this tutorial, you will not be using any of the extensions but you will need all of them in place if you wanted to try out the AndEngine sample project, which is also available on GitHub.
The sample project is a great way to learn the different ways to use AndEngine and you can always get the latest sample project and the extensions by downloading each of them from GitHub, setting up the projects, and building the sample. However, that is probably beyond the scope of this tutorial and so we’ll leave that to you to figure out, if you’re interested :] You can find it all at https://github.com/nicolasgramlich.

Setting Up the Environment

Before you start coding, there are a few things you should know about AndEngine:
  • OpenGL ES 2.0: The currently developed version of AndEngine is the GLES 2.0 version. This version requires OpenGL ES 2.0 support in order to function. So you need to make sure that your device (or emulator) supports OpenGL ES 2.0. If you are using the emulator to test, then you need graphics acceleration support and this is there only in the latest SDK Tools version. As of this tutorial, the latest SDK Tools version available is revision 19. Make sure that you have at least this version installed. To upgrade, please follow the instructions given here.
  • Android 4.0.3: You also need Android SDK Platform API 15, Revision 3 or higher in order to test OpenGL ES 2.0 based code on the emulator. So make sure that you’ve upgraded to at least Android 4.0.3, which is API 15. You emulator used for testing AndEngine code should be using Android 4.0.3.
  • Emulator: If you are using the emulator to test AndEngine code, you need a virtual device which has GPU emulation enabled and is running at least Android 4.0.3. So check your virtual device configuration and edit it if your device is not set up appropriately.
Andengine3
With that done, it’s time to start Eclipse, the IDE usually used for Android development. So go ahead an start Eclipse.
The version of AndEngine that you downloaded from GitHub already contains an Eclipse project file. You can simply import that by going to File->Import … That should open the following dialog:
Andengine1
Select “Existing Projects into Workspace” from the dialog and click “Next”. A new dialog should open where you must specify the location of the AndEngine project. It looks something like this:
Andengine2
Click the “Browse” button and browse to the folder where you extracted the AndEngine source ZIP file. The existing project should be detected and show up automatically in the dialog. Click “Finish”. And you should have the project imported into your Eclipse workspace – it’s that simple :]
If by some chance the extracted source is missing the Eclipse project information, you can create a new project by going to File->New->Project. A window like the one shown in the image below will open. Select Android Project and click Next.
Give the project a name: I suggest sticking with “AndEngine.” Select the “Create project from existing source” option. Next click the browse button, go to the location of the AndEngine source code and select Open. Once you’ve found the right location, press Finish. This will create a new project called AndEngine that you can view in the project navigator.
Your AndEngine project is now ready. This way, you can add your AndEngine project as a library to your tutorial project and the AndEngine library will be compiled in as part of your tutorial project.

The Tower of Hanoi

Time to start making your first Android game!! The game for this tutorial will be a simple version of the Tower of Hanoi puzzle. The finished project will look like this:
The objective of the Tower of Hanoi is to move all the rings over to the third rod, while only moving one ring at a time and without placing a larger ring on top of a smaller one.
Start by creating a new project. Open Eclipse and go to File->New and select Project, then select Android Project. Fill out all the details. I used the project name “TowerOfHanoi” and the package name “com.tutorial.towerofhanoi.” Feel free to use any name you wish, though it will be easier to stay in sync with the tutorial if you follow the same naming conventions.
Next add AndEngine as a library to your project. Right-click on the project and select Properties. Select Android in the left panel of the pop-up window. You should see a window like the one below:
From here you can add the engine as a library to the project. Click the Add button to add the AndEngine project. Once this is done, click Apply and then Okay.

Start Your AndEngine

Now you can begin coding. Open the src directory for the project via the Eclipse project navigator. If you drill down, (and if you used the suggested names) you should find a Java file called “TowerOfHanoiActivity.java”. (If you opted to name the first activity created something else, then find that file.) Open this file.
In Android development, an Activity is a single focused thing which interacts with the user. For instance, when you start an app, you can have a login activity which allows the user to login using their authentication credentials. And if the user doesn’t have a login, you might provide a second registration activity which will allow them to create a login.
The first file created by the project is also an Activity. And the first thing to do in our project is to change the class that this Activity extends. Instead of extending the Activity class, you want to make it extend a class called SimpleBaseGameActivity. And it’s fairly simple to do that, but in order to refer to the SimpleBaseGameActivity class, we need to add a few import statements for it. So we add that first to the top of the file under the existing import line:
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
Note: Technically, you don’t have to always add the import statements first. You can always add your code in, look for the red underlines beneath classes, let the Eclipse code-fix tell you what import is needed and let it add the imports for you. But this might get a little bit confusing when you’re not sure which import to add when you get a several different choices. So in this tutorial, we’ll always add the imports first.
Now, just change the class definition line, similar to the following:
public class TowerOfHanoiActivity extends Activity {
To something like this:
public class TowerOfHanoiActivity extends SimpleBaseGameActivity {
The SimpleBaseActivity class provides additional callbacks and contains the code to make AndEngine work with the Activity life cycle. Each callback that it provides is used for a specific purpose. As soon as you extend this class, you’ll have to override three functions. Here is a brief description of each of those functions:
  • onCreateEngineOptions: This function is where you create an instance of the engine. Every activity that the game uses will have its own instance of the engine that will run within the activity lifecycle.
  • onCreateResources: This is the function where you’ll load all the resources that the activity requires into the the VRAM.
  • onCreateScene: This function is called after the above two callbacks are executed. This is where you create the scene for your game and use all the textures that you previously loaded into memory.
We will first add some empty placeholders for the above callbacks so that we have some skeleton code. Replace the existing contents of our TowerOfHanoiActivity class with the following (if you started with an automatically created Activity, you should have an onCreate method implementation):
@Override
public EngineOptions onCreateEngineOptions() {
    // TODO Auto-generated method stub
    return null;
}
 
@Override
protected void onCreateResources() {
    // TODO Auto-generated method stub
}
 
@Override
protected Scene onCreateScene() {
    // TODO Auto-generated method stub
    return null;
}
Next, create a few static variables. These will be private to our class. So add the following code right below the class definition line:
private static int CAMERA_WIDTH = 800;
private static int CAMERA_HEIGHT = 480;
These two static variables define the width and height of the camera that the engine will use. This means that the final dimensions of the game scene will be equal to the camera size and width.
Next, you’re going to write code to initialize an instance of the engine. But that code is going to require several import statements in order to function properly. So first add the following imports to the top of the file below the existing import statements:
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
Now, add the following code for the onCreateEngineOptions function, replacing the placeholder conent which is in there at the moment:
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, 
    new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
In the above code, you create a new instance of the Camera class. Then we use that camera object to create the EngineOptions object that defines the options with which the engine will be initialized. The parameters that are passed while creating an instance of EngineOptions are:
  • FullScreen: A boolean variable signifying whether or not the engine instance will use a fullscreen.
  • ScreenOrientation: Specifies the orientation used while the game is running.
  • ResolutionPolicy: Defines how the engine will scale the game assets on phones with different screen sizes.
  • Camera: Defines the width and height of the final game scene.
Take a step back for a moment. As you know, Android runs on a lot of devices with different screen sizes. Keeping this in mind, it becomes very difficult to resize the game scene for each device. AndEngine comes with a unique solution to this problem: it will automatically scale the game assets to fit the screen size of the device.
If you set your CAMERA_WIDTH/CAMERA_HEIGHT to 480×320 and someone runs it on a phone with a 800×480 screen size, your game will be scaled up to 720×480 (1.5x) with a 80px margin (top, bottom, left, or right). Notice that AndEngine keeps the same aspect ratio and scales the game scene to the closest possible value to the actual screen size.

Loading Game Assets to VRAM

Now that you’ve initialized an instance of the engine, you can load all the assets required by the Tower of Hanoi game into memory. First download the game assets here.
Next create a new folder within the assets folder already present in your project. To do this, right-click on the assets folder and select New->Folder, name the folder “gfx” and copy all the downloaded assets to that folder.
To load these assets, we’re going to add the onCreateResources method. But as you might guess, our new code references several other classes for which we need to add imports. So add the following at the top of the file below the rest of the import statements:
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.debug.Debug;
 
import java.io.IOException;
import java.io.InputStream;
Now, replace the placeholder content in onCreateResources with the following:
try {
    // 1 - Set up bitmap textures
    ITexture backgroundTexture = new BitmapTexture(this.getTextureManager()
new IInputStreamOpener() {
        @Override
        public InputStream open() throws IOException {
            return getAssets().open("gfx/background.png");
        }
    });
    ITexture towerTexture = new BitmapTexture(this.getTextureManager()
new IInputStreamOpener() {
        @Override
        public InputStream open() throws IOException {
            return getAssets().open("gfx/tower.png");
        }
    });
    ITexture ring1 = new BitmapTexture(this.getTextureManager()
new IInputStreamOpener() {
        @Override
        public InputStream open() throws IOException {
            return getAssets().open("gfx/ring1.png");
        }
    });
    ITexture ring2 = new BitmapTexture(this.getTextureManager()
new IInputStreamOpener() {
        @Override
        public InputStream open() throws IOException {
            return getAssets().open("gfx/ring2.png");
        }
    });
    ITexture ring3 = new BitmapTexture(this.getTextureManager()
new IInputStreamOpener() {
        @Override
        public InputStream open() throws IOException {
            return getAssets().open("gfx/ring3.png");
        }
    });
    // 2 - Load bitmap textures into VRAM
    backgroundTexture.load();
    towerTexture.load();
    ring1.load();
    ring2.load();
    ring3.load();
} catch (IOException e) {
    Debug.e(e);
}
In the above code, you first create an ITexture object. ITexture is an interface. An object of this type is initialized to a BitmapTexture object, which, you guessed it, is used to to load a bitmap into VRAM. The above code creates ITexture objects for all the assets you downloaded, and loads them into VRAM by calling the load method on each object.
Now that you have all your assets loaded, you need to extract TextureRegions from your textures. Think of a texture as a giant canvas that has to have width and height values which are a power of 2 (a requirement of OpenGL ES). A TextureRegion, on the other hand, is a part or a region of a texture that does not have to have dimensions which are a power of 2.
Note: Instead of creating textures for each of your assets, you could have loaded all the assets into one texture and extracted the individual assets as TextureRegions. Doing this is out of scope for this tutorial, but I may cover it in detail in a future tutorial.
As you might guess, we have to add a few new import statements first:
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
Now, to hold the TextureRegions, add private variables to our class (again, at the top of the file, below the previous private variables):
private ITextureRegion mBackgroundTextureRegion, mTowerTextureRegion, mRing1, 
mRing2, mRing3;
Finally, add these lines of code to onCreateResources, right after the end of section #2 where you load the bitmap textures into VRAM:
// 3 - Set up texture regions
this.mBackgroundTextureRegion = TextureRegionFactory.extractFromTexture(
backgroundTexture);
this.mTowerTextureRegion = TextureRegionFactory.extractFromTexture(towerTexture);
this.mRing1 = TextureRegionFactory.extractFromTexture(ring1);
this.mRing2 = TextureRegionFactory.extractFromTexture(ring2);
this.mRing3 = TextureRegionFactory.extractFromTexture(ring3);
The above code initializes your TextureRegions using the textures that you already loaded into VRAM.

Creating the Game Scene

It’s finally time to create the game scene! Of course, we need another new import:
import org.andengine.entity.sprite.Sprite;
Next, replace the placeholder content in onCreateScene with the following:
// 1 - Create new scene
final Scene scene = new Scene();
Sprite backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion
getVertexBufferObjectManager());
scene.attachChild(backgroundSprite);
return scene;
The above code first creates a Scene object. Next you create a sprite called backgroundSprite and attach the sprite to the scene. Notice that this method requires you to return the scene object. Think of a scene as a container with a number of layers, and each layer can have many sprites (TextureRegions) placed within it.
When creating a Sprite object, you pass four parameters. Here’s a brief description of each parameter:
  • xCoordinate: Defines the X-position of the sprite. The AndEngine coordinate system considers the top-left point as the origin.
  • yCoordinate: Defines the Y-position of the sprite.
  • TextureRegion: Defines what part of the texture the sprite will use to draw itself.
  • VertexBufferObjectManager: Think of a vertex buffer as an array holding the coordinates of a texture. These coordinates are passed to the OpenGL ES pipeline and ultimately define what will be drawn. A VertexBufferObjectManager holds all the vertices of all the textures that need to be drawn on the scene.
Compile and run the application. You should see something like this:
Nice, we’re starting to see something! However, this platform does look a little bit desert-ed (groan) ;]

The Three Towers

It’s time to add the sprites for the towers and rings – the final step before getting things moving with the game logic. Start by adding three private variables to the class. Declare the variables as follows:
private Sprite mTower1, mTower2, mTower3;
Next add the following lines of code to onCreateScene, right before the final return statement:
// 2 - Add the towers
mTower1 = new Sprite(192, 63, this.mTowerTextureRegion
getVertexBufferObjectManager());
mTower2 = new Sprite(400, 63, this.mTowerTextureRegion
getVertexBufferObjectManager());
mTower3 = new Sprite(604, 63, this.mTowerTextureRegion
getVertexBufferObjectManager());
scene.attachChild(mTower1);
scene.attachChild(mTower2);
scene.attachChild(mTower3);
You’ve defined three sprites, each using the TextureRegion of the tower that you loaded in onCreateResources.Then you added these sprites to your scene. That’s all there is to it!
Compile and run. You should now see the three towers placed in their proper positions.

And One Ring to Bind Them

Let’s talk a little about the game logic before you create your rings. Think of the towers as three stacks (I mean the data structure) – you can only remove the top-most element, and when you add an element it will always be on top. You’ll use these stacks when you write the game logic code.
To create the rings, we need to first make a custom class that will extend Sprite. You do this because every ring needs to know which stack it belongs to.
Right-click on the folder containing TowerOfHanoiActivity.java and select New->Class. You should see a dialog which you should fill in similar to the following:
Andengine4
Note that you probably would have “Source folder” and “Package” filled in automatically. All you’d need to do is type in the “Name” and click “Browse…” next to “Superclass” to find the Sprite class from AndEngine. That should create a Java file called “Ring.java.” Place the following code within the class implementation (after the public class line and before the closing curly brace):
    private int mWeight;
    private Stack mStack; //this represents the stack that this ring belongs to
    private Sprite mTower;
 
    public Ring(int weight, float pX, float pY, ITextureRegion pTextureRegion, 
VertexBufferObjectManager pVertexBufferObjectManager) {
        super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
        this.mWeight = weight;
    }
 
    public int getmWeight() {
        return mWeight;
    }
 
    public Stack getmStack() {
        return mStack;
    }
 
    public void setmStack(Stack mStack) {
        this.mStack = mStack;
    }
 
    public Sprite getmTower() {
        return mTower;
    }
 
    public void setmTower(Sprite mTower) {
        this.mTower = mTower;
    }
Most of the code here is pretty straightforward. The object has three private variables. One is used to keep track of the weight of the tower; this is an integer value, i.e., the higher the value, the bigger the ring. The other two variables are used to store the stack that the ring belongs to and the tower on which it is currently placed.
You’ll also need to add the following import statements to the top of the file:
import java.util.Stack;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
Now that we have the Ring class, to create and add the rings, add the following lines of code to onCreateScene, right before the return statement:
// 3 - Create the rings
Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager());
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager());
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager());
scene.attachChild(ring1);
scene.attachChild(ring2);
scene.attachChild(ring3);
Compile and run to test.
Andengine5
You’ll notice that the rings are now on the first tower but you can’t move the rings. That’s because we haven’t worked out the game logic for placing and moving the rings. So that’s what you’ll do next :]

Game Logic

Ready to bring your Tower of Hanoi puzzle to life? As mentioned before, as the foundation of the game logic, you’re going to create three stacks, each representing a tower. Start by adding the following import for the Stack class to TowerOfHanoiActivity.java:
import java.util.Stack;
Next, declare the stack variables below the other private variables:
private Stack mStack1, mStack2, mStack3;
You’ll initialize these variables in onCreateResources. Add the following lines of code after the end of section #3:
// 4 - Create the stacks
this.mStack1 = new Stack();
this.mStack2 = new Stack();
this.mStack3 = new Stack();
When the game starts, all three rings should be in the first stack. Put the following code in onCreateScene right before the return statement:
// 4 - Add all rings to stack one
this.mStack1.add(ring3);
this.mStack1.add(ring2);
this.mStack1.add(ring1);
// 5 - Initialize starting position for each ring
ring1.setmStack(mStack1);
ring2.setmStack(mStack1);
ring3.setmStack(mStack1);
ring1.setmTower(mTower1);
ring2.setmTower(mTower1);
ring3.setmTower(mTower1);
// 6 - Add touch handlers
scene.registerTouchArea(ring1);
scene.registerTouchArea(ring2);
scene.registerTouchArea(ring3);
scene.setTouchAreaBindingOnActionDownEnabled(true);
In the above code, you do the following:
  1. Added the rings to the first stack.
  2. Set the stack variable of each ring as the first stack and the tower variable as the first tower.
  3. To handle touch and movement of the rings, you registered each ring as a touchable area.
  4. Enabled touch binding.
Now, you need to override the onAreaTouch method of the Sprite class. This is where you’ll add logic to move the rings. But that code in turn will require a method which checks whether a ring collided with a tower. You’ll write that code later, but you need to add an empty method place holder for collision detection as follows (you can add this to the end of the class):
private void checkForCollisionsWithTowers(Ring ring) {
}
You also need to add the following import in order for the ring movement code to be able to identify the relevant classes:
import org.andengine.input.touch.TouchEvent;
Now, replace the first three lines of section #3 in onCreateScene (where you defined the rings) with the following:
Ring ring1 = new Ring(1, 139, 174, this.mRing1, getVertexBufferObjectManager()) {
    @Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, 
float pTouchAreaLocalX, float pTouchAreaLocalY) {
        if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
            return false;
        this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, 
            pSceneTouchEvent.getY() - this.getHeight() / 2);
        if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
            checkForCollisionsWithTowers(this);
        }
        return true;
    }
};
Ring ring2 = new Ring(2, 118, 212, this.mRing2, getVertexBufferObjectManager()) {
    @Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent, 
float pTouchAreaLocalX, float pTouchAreaLocalY) {
        if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
            return false;
        this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, 
            pSceneTouchEvent.getY() - this.getHeight() / 2);
        if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
            checkForCollisionsWithTowers(this);
        }
        return true;
    }
};
Ring ring3 = new Ring(3, 97, 255, this.mRing3, getVertexBufferObjectManager()) {
    @Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent,  
float pTouchAreaLocalX, float pTouchAreaLocalY) {
        if (((Ring) this.getmStack().peek()).getmWeight() != this.getmWeight())
            return false;
        this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, 
            pSceneTouchEvent.getY() - this.getHeight() / 2);
        if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
            checkForCollisionsWithTowers(this);
        }
        return true;
    }
};

Notice that onAreaTouched returns a boolean value. When it returns true, the touch is consumed, otherwise it is passed down to other layers until someone consumes it. So the first thing you do in this method is check if the weight of the current ring is not equal to the weight of the first ring in the stack. If it is, that means this ring is the first element of the stack and so you can proceed to move it, otherwise you let the touch go since you can’t move this ring.
You also check in onAreaTouched if the type of touch is an ACTION_UP event, triggered when the finger is lifted. If it is, you call checkForCollisionsWithTowers whose primary purpose is to check if the ring has collided with (or rather, is touching) a tower. As you may recall, you added a placeholder for checkForCollisionsWithTowers already. Let’s fill the function in now.
Replace the placeholder method for checkForCollisionsWithTowers with the following:
private void checkForCollisionsWithTowers(Ring ring) {
    Stack stack = null;
    Sprite tower = null;
    if (ring.collidesWith(mTower1) && (mStack1.size() == 0 ||             
            ring.getmWeight() < ((Ring) mStack1.peek()).getmWeight())) {
        stack = mStack1;
        tower = mTower1;
    } else if (ring.collidesWith(mTower2) && (mStack2.size() == 0 || 
            ring.getmWeight() < ((Ring) mStack2.peek()).getmWeight())) {
        stack = mStack2;
        tower = mTower2;
    } else if (ring.collidesWith(mTower3) && (mStack3.size() == 0 || 
            ring.getmWeight() < ((Ring) mStack3.peek()).getmWeight())) {
        stack = mStack3;
        tower = mTower3;
    } else {
        stack = ring.getmStack();
        tower = ring.getmTower();
    }
    ring.getmStack().remove(ring);
    if (stack != null && tower !=null && stack.size() == 0) {
        ring.setPosition(tower.getX() + tower.getWidth()/2 - 
            ring.getWidth()/2, tower.getY() + tower.getHeight() - 
            ring.getHeight());
    } else if (stack != null && tower !=null && stack.size() > 0) {
        ring.setPosition(tower.getX() + tower.getWidth()/2 - 
            ring.getWidth()/2, ((Ring) stack.peek()).getY() - 
            ring.getHeight());
    }
    stack.add(ring);
    ring.setmStack(stack);
    ring.setmTower(tower);
}
The above code checks whether the given ring is touching a tower, if it is, whether it can be moved to that tower, and if yes, places the ring appropriately.
Build and run, and you should have a completely functional Tower of Hanoi game! There are only three rings, but that means you should be able to beat the game in no time. :P



Source : here

Cara Menghemat Daya Baterai Hp Android Anda

Sistem operasi android kini semakin populer saja, pemilik hp android pun makin bertambah, termasuk Anda mungkin. Sistem operasi besutan Google ini hadir dalam berbagai jenis dan merk perangkat portabel seperti Samsung, HTC, Sony, dan banyak lagi.
Salah satu kelebihan hp android adalah kita dapat mendownload banyak aplikasi yang dapat berguna bagi kegiatan kita sehari-hari, menariknya berbagai aplikasi tersebut terhubung langsung dengan internet setiap saat, sehingga kita dapat menerima email atau memaca berita yang selalu update setiap waktu.
Namun, kelebihan hp android yang selalu terhubung ke jaringan internet tersebut yang seringkali menjadi alasan kita kehabisan daya baterai pada hp android. Seringkali kita melihat baterai hp android kita terkuras padahal kita tidak terlalu aktif memakainya. Apakah hal ini terjadi pada hp abdroid Anda? Berikut ini beberapa trik untuk membuat hp android Anda hemat baterai.

1.  Mengalihkan Koneksi
Tidak stabilnya sinyal data 3G yang hp android kita tangkap dapat membuat hp kita terus bekerja keras (menguras baterai) mencari sinyal terbaik. Untuk lebih menghemat daya baterai sebaiknya saat kita dalam lokasi HotSpot, kita mematikan koneksi selular kita dan mengkoneksikan hp android dengan WiFi yang tersedia. Seperti dirumah, kantor atau mall, kapanpun ada WiFi maaka alihkanlah jaringan internet ke WiFi, lagipula umumnya koneksi dengan WiFi lebih cepat dibanding dengan selular, sehingga hp android Anda akan membutuhkan waktu yang lebih singkat untuk “load” saat Anda browsing atau memakai aplikasi yang membutuhkan koneksi internet.

2. Matikan WiFi & Bluetooth
Hal ini sering terlewat oleh para pengguna hp android, yaitu mematikan WiFi. Saat tidak memerlukan koneki WiFi sebaiknya kita mematikan koneksi WiFi kita. Karena bila WiFi hidup maka hp android kita akan terus aktif mencari sinyal WiFi dan hal ini akan membuat terkurasnya baterai hp android. Begitu juga dengan fasilitas Bluetooth, fasiltas untuk kita dapat bertukar data ini sebaiknya dimatikan bila kita tidak sedang memerlukannya, toh menyalakannya juga tidak repot yaitu dengan Gulir kebawah pada home screen, tap pada ikon bluetooth

3. Matikan GPS
Fasilitas GPS pada hp android seperti kita tahu sangat berguna untuk mencari jalan atau kita sedang tersesat, namun pemakaian GPS tidaklah terlalu sering, kita tidak setiap hari tersesat bukan? Maka matikanlah fasilitas GPS hp android Anda, dan hidupkan hanya bila Anda memerlukannya. Caranya sangat simple yaitu Gulir kebawah pada home screen, tap pada ikon GPS

4. Mematikan Fitur Sync
Hp android memudahkan Anda mengetahui notifikasi email, facebook dan aplikasi lain secara live, namun bila Anda sedang tidak terlalu memerlukannya seperti saat liburan atau diperjalanan maka sebaiknya matikan fitur sync ini, namun konsekuensinya Anda tidak akan menerima notifikasi-notifikasi tersebut. Jangan khawatir, Anda tetep bisa melihat update terbaru dengan masuk ke aplikasi  yang Anda ingin lihat updatenya.

5. Kurangi Brigtness Layar
Keindahan hp android adalah pada layarnya yang memberikan Anda warna nyata nan menabjubkan apalagi bila hp Anda seperti Samsung Galaxy terbaru yang sudah memakai teknologi Super Amoled. Namun, layar hebat ini termasuk faktor terbesar baterai hp android Anda terkuras, jadi rendahkanlah pada kondisi gelap dan naikan sedikit saja bila kondisi ruag terlalu terang.

6. Kurangi Volume & Matikan Getar
Untuk point yang satu ini mungkin sangat umum digunakan pada semua ponsel, hampir semua orang tahu bahwa fitur getar pada hp dapat menguras baterai, sehingga sebaiknya matikan fitur getar (vibrate) dan kurangi volume untuk lebih hemat baterai.

7. Dapatkat Aplikasi Task Killer atau Baterai Dr. Saver
Aplikasi-aplikasi yang tersedia pada pusat download pada hp android kini banyak yang dirancang untuk meningkatkan kinerja dan menghemat baterai hp android Anda. Contohnya adalah Task Killer atau Baterai Dr. Saver, kedua aplikasi ini berkonsep sama yaitu mematikan aplikasi yang sedang berjalan dibelakang yang tidak terlihat, dengan aplikasi yang tertupu tentunya hp android Anda tidak bekerja terlalu keras sehingga baterai pun dapat lebih dihemat.



Sumber : disini