How to Create a Simple Android Game with AndEngine

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

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

This is a blog post by iOS Tutorial Team member Ali Hafizji, an iOS and Android developer working at Tavisca Solutions.

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

Where to Go From Here?

Here is the complete source code of the project.

There are a number of things left to be done, but these are easy enough to accomplish. So I’m going to leave them as an exercise for you :] Possible additions include:

  • Detecting when all the rings have been moved to the third tower and showing a Game Over pop-up.
  • Counting and displaying the total number of moves.
  • Calculating and displaying the minimum number of moves required. (Hint: with three rings, the puzzle can be solved in seven moves.)
  • Allowing the user to increase the difficulty by adding more rings. Legend has it that there is a temple where the priests are working on a version of this puzzle with 64 rings! I don’t suggest you create a version of this game with that many rings, unless you want to spend 580 billion years solving it!

Try your hand at these improvements and let me know how you fare in the forums!

Also let me know if you’d like to see more tutorials about AndEngine – I could write more about AndEngine’s extensions and how you can use each of them in a game. Until then, happy coding :]

This is a blog post by iOS Tutorial Team member Ali Hafizji, an iOS and Android developer working at Tavisca Solutions.

Ali Hafizji
Ali Hafizji

Ali is a full time iOS developer currently working at Tavisca solutions. He is an avid programmer and loves learning better and faster ways of solving problems. You can follow him on Twitter or github.

User Comments

44 Comments

[ 1 , 2 , 3 ]
  • i m at the half way of this tutorial...trying to show the backGround image...my API version is 15...and minimum sdk is 2.2....but i have not been able to show the backGround image...instead of the image....a triangle has been showed...in the emulator(4.03) it is been forced close and in my cellPhone which is 2.3.3...a triangular part of the image is shown...please give me some solution... i m very xcited to found such a good tutorial on andengine...but getting frustrated for being stuck at this position for so long...plz suggest me something..

    thank you very much
    dipayan
  • after doing everything you said...there is only the background image and the towers...but no rings are displayed....rings were showed when they were initially attached...can you give me some solution please...thank you
    dipayan
  • Nice tutorial, but sometimes, when dragging a sprite towards another stack it gets stuck in the middle of the screen when releasing, instead of returning to the initial position or the stack you drag it to. Fairly easy to reproduce by dragging using two fingers on two blocks.

    I debugged it and the ACTION_UP event is not being fired in that case, leaving the object "hanging" on it's last position.

    Anybody else noticed this problem?
    monadx
  • Awesome Tutorial !!

    Very good job !!
    Wahid
  • Thank you so much for this tutorial, all of the examples I've found for AndEngine so far will not work, but I had no problem following your example and I actually feel like I can get into learning AndEngine now. I created an account just to thank you! :P I'd be all about seeing more examples for this engine. Thanks again, Ali, you're a lifesaver!
    FootSoldier
  • Thanks for this great tutorial! Hopefully looking forward to other tutorials with AndEngine (and maybe Box2d ?) ;) !
    Best regards, Eli
    eli_w
  • This is an amazing tutorial. Specially, the way you have shown how to build the code section by section. The logical flow of explaining has also been awesome. Would love to read more blogs of yours regarding AndEngine and its plugins. Please carry on the good work :)!
    anirbanbm
  • Hey I really need someones help. First issue im havong is that my camera is half off the screen. for example, my camera width is 800 and when the position is set to 400, the sprite is at the left most side of the screen.
    Second, to get the rings on the x axis placing properly, i have to set them all at the same x coordinate. any help would be aprreciated
    android4life
  • Hi Ali,
    Just want to say thank you for sharing this game tutorial. I've been learning java android for a few months and just started researching gamification. Your Tower of Hanoi tutorial was a nice learning experience.
    Best Wishes,
    Monica
    monigarr
  • harharmahadev
    Sangeeta
  • As far now I had been working Apps . Thought of moving into Gaming Apps and found this tutorial very useful and I successfully able to develop my first Android game App.
    Thanks a lot :)
    Sangeeta
  • Awesome Tutorials. Thanks.
    kalpeshhiran
  • In applying the "Game Over" once the rings reach the 3rd tower. Where do I insert the code and where do I begin?
    rsiasat00
  • Awesome tutorial, clear and concise.
    aerisvulpe
[ 1 , 2 , 3 ]

Other Items of Interest

Ray's Monthly Newsletter

Sign up to receive a monthly newsletter with my favorite dev links, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

Hang Out With Us!

Every month, we have a free live Tech Talk - come hang out with us!


Coming up in May: Procedural Level Generation in Games with Kim Pedersen.

Sign Up - May

Coming up in June: WWDC Keynote - Podcasters React! with the podcasting team.

Sign Up - June

Vote For Our Next Book!

Help us choose the topic for our next book we write! (Choose up to three topics.)

    Loading ... Loading ...

Our Books

Our Team

Tutorial Team

  • Jake Gundersen

... 55 total!

Editorial Team

  • Alexis Gallagher

... 21 total!

Code Team

  • Orta Therox

... 1 total!

Translation Team

  • Rodrigo Salles

... 38 total!

Subject Matter Experts

... 4 total!