Friday, 5 August 2011

Tetris clone on Android: Day 2

Hi guys! I've been working on the design of my Tetris clone game and some minor adjustments like adding hold and drop function. The design is a bit rough. I even forgot to have my power nap :D. I was having fun doing this. I would also like to share to you about vibrations on Android. It would be nice if the user can feel they clicked on something by adding a what they call "Haptic Feedback". So I added a vibrate function and add it in my game engine.

This is how to initialize a Vibration on Android:

Vibrator vibrator =(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

To make your Android device vibrate, you need to call the vibrate() method with a parameter of type float which is the time needed for it to vibrate.


I still need to refine the input system cause it seems a little bit off when using.

Thursday, 4 August 2011

My Tetris clone on Android

Hi guys! Today, I'm back to developing Android applications and my first step is making a tetris clone. I based it  on my XNA implementation of tetris a year ago. The code that I followed is made by Javier Lopez's tutorial on making a tetris clone in C++ (Credits to him I learned a lot when I was still studying :D). He has a very good and clean code (Clean enough for C++ implementation) which made it easy to implement on various platforms including Android (Windows, XBOX, iPhone, name it!). I've gone through many tutorials on making a Tetris clone but this ones the best I could see (I bought a book before about game development which has a chapter focusing on developing a tetris clone, It sucks! It's so language specific and complex).

My Tetris clone in a Emulator
I based my work on my dirty game engine. I'm still continuing to develop this app and I will base my future game (Similar yet very different to tetris) on this. I'm glad to be back on developing Android applications! :D

Tuesday, 2 August 2011

Wallpapers Part 2

Hi everyone,

I will post new android wallpapers I just made recently. Hope you like it. You can also download all of the wallpapers here.

Monday, 1 August 2011

My feelings Wallpaper

Hi guys! Today, me and girlfriend celebrated our years of love and happiness together :D (I can't count the number of months with my fingers and toes already). I'd like to share to you images that I created in Adobe Photoshop about some of my feelings that I experience every time I receive money. I made this out of wanting to manifest abundance in my life. Check these out:

I would like to make more wallpapers about feelings. I made them as simple as possible, emphasizing the text in the center.

You can download the 4 of these wallpapers here.

Saturday, 30 July 2011

Make your Android device into a killer game console with "Inotia 3: Children of Carnia"

Few days ago, I was a bit busy working on a certain project and at the same time, I glued my eyes on a game I got interest to. This game was titled: "Inotia 3: Children of Carnia". I was a bit curious because I saw the pictures about it which has great graphics (comparable to a GameBoy Advance or sort) so I tested it out. It really have great graphics, very stunning indeed :D. The game was RPG (with all those hack and slash thingy). The story revolves around a boy named Lucio (the main character of the game) and his (probably) past life as Laciel (much like the hero in the game's world). In the game, you start out by preparing for Lucio's "Adulthood Ceremony", you do some chores for other people (like most RPG nowadays). Lucio's adventure started when he stumbled upon a dying orc which then gave him a gauntlets which happens to be powerful. The gauntlets led him to a series of adventures and perils, meeting friends and enemies that are also looking for it. Everything happened to him was fate after all, knowing that he was the chosen one (he disagrees this at the very beginning even if powerful spirits tell him he was).

In the game, you get to choose from different classes with different strengths and abilities. You get to fight along with other characters or hire mercenaries in the game which you could also use. Enjoy the game with hundreds of game maps, items and quests. The best part of the game is the graphics. I could actually compare this game with other games found in various consoles. Try using the Arch Mage class and feel the power with the intensity of the graphics hitting to enemies at its wake. I got my eyes glued on this game for straight 5 days.

My only problem with the game is that it constantly hangs up (Showing the game is indeed very heavy). I am forced to skip cut scenes and sounds to make it a bit playable but still it hangs up (I even tried to make the graphics option lower). To slower Android devices like mine, don't even bother playing at all, you'll get frustrated.

Download Inotia 3: Children of Carnia here.

Have fun!! :D

Thursday, 28 July 2011

Chikka for Android

Chikka: STILL the best way to send FREE TEXT MESSAGES to the philippines.

What's with the big "STILL"? because it is now available on your Android Device! :D Imagine all you can text with this app. Chikka has made a lot of improvements on their services: like their desktop version, facebook app, iPhone, and Android. There are many ways to send text messages on the web, but Chikka is proven and tested. Used by a lot of Filipinos to send free text messages via the internet. Users can chat or send text messages to everyone using the internet. That's good news to everyone. So why waste your cellphone load if there is a way to send free text messages?

Too good to be true? well, not much. There are some flaws to this app (Though I don't get these flaws usually). Some say that they cannot receive the messages (sometimes late) while others cannot view their buddy list. But all these does not keep you from sending free text messages so no worries.

For new users, all you need is to register in Chikka. It's easy to register, you only need to provide your mobile number and your email address. Now, you can send free text messages without wasting your cellphone load, even when you're abroad! (outside the Philippines of course :D)

Download this app in the market here.

Wednesday, 27 July 2011

Mango: Manga Readers, Rejoice!

Are you also a Manga Fanatic like me? Been reading Naruto, Bleach, and One Piece lately? Do you want reading manga not on your browser? Now here it is: Mango - a manga reader with slick design, fast download, over 8,000 titles and updating, and other features like offline reading, bookmarking, and the best part, its free!

Mango is a free manga reader app on Android (they also have blackberry). This app is the best manga reader available on Android. You could search for your favorite manga title. Read it with ease with its pinch to zoom function, gesture controls, jump-to-page, and a lot more! I don't even experience a bit of sluggishness (unlike Adobe Reader) because it's real fast! Every manga reader should have this app.

More of the talking: Download this app here.

You'll love it more when you try it.

The Android Story: Timeline of our small, green robot

While reading my daily news in CodeProject(one of my favorite sites :D) I've come across this giant timeline telling the story of Android. Click on the image to view it


Infographic by Android Developers at [x]cubelabs

Monday, 25 July 2011

Meet my Android: Samsung Galaxy 5 (I5500)

Yeah! this is my Android smartphone. The Samsung i5500 (more known in the Philippines as Samsung Galaxy 5). It is powered by Eclair (Android 2.1, upgradable to 2.2) with 2MP camera, GPS, Accelerometer, 240X320 pixels 2.8 inch display. Because its Android, you'll get most of it with all the apps in the market, all the tweaks and hacks available to it (I recommend reading this blog if you want to upgrade your Samsung i5500 to Android v2.2).

Make everyone drool by adding high powered apps and games that makes your Samsung i5500 into a Nintendo DS (this happened when I add Inotia 3 on my phone). Be an IT Expert by adding different networking tools, web development applications, code viewers, and different home brewed apps you made. Show your business partners your presentation works, business flowcharts, and financial statistics, using your personal "Android" assistant (PAA instead of PDA). That's how powerful your Samsung i5500 will be (not to mention google's apps like YouTube, Music Player, etc). Whats more? its one of the cheapest in the market! There's more to discover when it comes to Android. You('ll) know what I mean.

I made my phone go super soldier by upgrading it to Android 2.2 with a lot of unlocked features like App2SD and Bluetooth/USB/Wifi Thetering. Rooted it to add more power using Universal Androot. Added with root only apps (careful installing root only apps, not all are as helpful as you think). WARNING: Doing these things require more responsibility to the user.

Part 3 of this post is the cons of this phone. First impression, short battery life. Yeah most phone does die out. Constantly freezes when you use a hard core app (particularly HD games, try restarting your phone if it does). Samsung's Kies, their PC-Android smartphone sync software, is very buggy and you need 1gb of RAM just to run that software (Thank God I love Android, or else... :D).

You want Android at a very affordable price with a good customer service? Why not try Samsung i5500 (Galaxy 5) out.

Friday, 22 July 2011

Fruit Ninja: Enter the clan

Feel like being in the "Ninja World" of Naruto? Is your hands as fast as the "Yellow Flash". Are you craving for fruits? Here's your chance to be a  part of the Fruit Ninja Clan!

One of the best games I played on my Android phone is Fruit Ninja. An excellent action game wherein players slash fruits to score up. As what Sensei (The old man you always see on the game) says: Ninjas Hate Fruits. Its very addictive and challenging. It features worldwide leaderboards via OpenFeint, making you want to be on top of all Ninjas scattered across the world. It has 3 game plays: Classic for slashing fruits and evading bombs, Zen mode for time trialed action, and the new Arcade mode which features power ups. You can also unlock a number of swords and backgrounds that you will use in the game. This game is satisfyingly fun! You'll never take your eyes off of it.

Are you up for the action? Download the game on Android here. You can also view their website.

Angry Birds: Why I love them

Angry Birds

Everyone knows them. Everyone loves them. Everyone is a big fan of them. They have them on their smart phones, browsers, stuffed toys, wallpapers, bags, t-shirts, they are everywhere you can imagine! Angry Birds is like a virus spreading everywhere. This enjoyable physics game is so much fun. It has been a big hit since it was made. The game play is so addicting. I can't even take my eyes off it. The objectives is simple, destroy all pigs with those birds. You, as a player, are armed with a slingshot to throw those birds to were the greedy pigs are hiding. You can directly destroy them, or hit structures that will fall to them (That certainly hurts in real life too :D).

When I was a game development trainee back then. I always play Crush The Castle 2 on I became addicted to it, the game was fun, I can throw various weapons to castles (my favorite is the poison potion thingy that melts everything in its wake). After I finished the game, I was looking for similar games, so I searched google on "Throwing Games, Physics, etc." and found Angry Birds. First impression was the characters are cute (notice their eyebrows??? :D). So I watched a video in you tube about it. I said "SHIT THEY'RE THROWING THE BIRDS!!!". God I was shocked. It was very funny, I enjoyed watching the game (I even forgot my work). The time I bought my Android handset, I immediately downloaded Angry Birds, played it, until 3 in the morning (Wahahhahahha :D I still have my job back then).

Hours of crushing objects, green colored pigs, and the birds faces (Notice that when the bird lands on anything). Each Angry Bird has its unique special moves which adds more fun to the game. Destroying structures with your wits is very fun. Whats more? You could have more fun with their free updates. I always wonder why the pigs are GREEN. You could download the game on Android here.

Wednesday, 20 July 2011

Game Dev Story: Addicting and Fun

Lately on my Android life, I found a game that interests me (somehow, hehehe) on the Android Market with the title Game Dev Story. At first, I thought this game is somewhat technical (particularly in making games, which is also my interest), so I downloaded its "Lite" version to test it out. Graphics are somewhat like the games you see on GameBoy with a button telling me to play this game (actually it is labeled as "new game", hehehe). I was then brought to a world identical to ours but me as a president of "Sunny Studios". I found my Secretary welcomes me and tells me to hire new employees. Your ultimate goal, as the president of your company, is to be on top of the video game industry.

Now lets get back to the real life. Your Secretary in the game tells you hints while your still familiarizing the game. You have about 2 employees (that are doing nothing at the very beginning). You can add your employees by hiring. You can do many things to your employees like training them (training boosts their stats, making them more productive in making games), level them up (same as training but their salaries increased, ouch), change their careers (change their job description when they are at maximum level, which is Lvl 5, and rotate their jobs until you get an option making him/her a Hardware Engineer), give them items that boosts their stats, and fire them (ouch).

You make your company productive by doing jobs outside (contracts) and making games (new game). Contracts gives you small but fast cash (you need to finish the job of course). Making games, like real life, is expensive. You need to purchase licenses to develop for a console (BTW, there are many consoles in the game), choosing a genre and a type of game also has a price, even the development process (direction of the game).

To much of the expenses, lets go through the return of your investments. Actually, the money you make by making a game depends on your game. So you need to make sure you have the right combinations of genre and type (there are many in the internet you can find), employees with good stats, good timing (which is usually december), and the right console. Not all consoles in the game gives you a lot of money (The game consoles in Game Dev Story are real life consoles, with different names and design of course. Choose the ones that look like a Game Boy and a Play Station). To ensure you have many sales, you must advertise your game to make many fans. The more fans you have, the more sales you get.

I wasn't able to continue my quest as a president of "Sunny Studios" because I just downloaded the lite version. Even so, It was addicting and fun! I love the game. Even my girlfriend is enjoying this game. The technicality of making a game was simplified by a game making it more fun and enjoyable. As a game developer, I learned a lot from this game.

I want you to try it out. You can download the game in the Android Market:

The game is also available on iPhone.

Tuesday, 19 July 2011

Cherry Mobile Cosmo: Cheapest Android Phone

Yesterday, I blogged about a list of Android handsets below Php 10,000 (around USD 235). Today I will be blogging about the cheapest in the list, Cherry Mobile Cosmo.

Cherry Mobile Cosmo
Php 6,800

For as low as Php 6,800 (around USD 159), you can now have a Android 2.2 (Froyo) running device packed with 2mp camera with internal memory of 512 mb (minus the Android thingys) and expandable memory up to 16 gb. Cool Isn't it? Cherry Mobile has been making Android devices (Nova and Superion to name a few) and ever since I've been expecting them to bring the cheapest on the market (though Huawei Ideos was the first handset I saw with the cheapest price first :D). This makes me think twice when I bought my Samsung Galaxy 5 on Php 8,000 (around USD 187) with Android 2.1 (Eclair). Cherry Mobile has been offering cool but cheap mobile phones around 2 years or so ago (Not to mention the calculator like mobile phone :D). I'm not quite sure if this phone is already available in your nearest cell shops (I'm sure in mine. hehe :D) because some say its not available in theirs.

Here is a full list of specifications provided by Cherry Mobile.:
  • Android 2.2 (Froyo)
  • Qualcomm MSM 7227 600Mhz
  • 3.2" HVGA Capacitive Touchscreen
  • ROM: 512MB / RAM: 256MB
  • Dual Band GSM / GPRS / EDGE
  • 2MP Camera
  • Portable Wifi Hotspot
  • WIFI / Bluetooth / 3G / GPS
  • FM Radio
  • Standard Micro USB 2.0
  • 3.5mm Stereo Audio Jack
  • Expandable Memory up to 16GB

Cheap Android Phones in the Philippines

Want to buy an Android phone, but are low in cash? Well there is good news, you can now get Android handsets for Php 10,000 or below. There are many devices to choose from. Below are a list of affordable Android smartphones (Click on the links to see each's specs):

Samsung Galaxy Fit S5670 – Php10,000

LG Optimus One P500 – Php9,800

Sony Ericsson X10 Mini – Php9,000

Samsung Galaxy Mini S5570 - Php8,500

Sony Ericsson X8 – Php8,000

Cherry Mobile Nova – Php8,000

Samsung Galaxy 5 i5503 – Php8,000

Huawei Ideos U8150 – Php7,000

Cherry Mobile Cosmo – Php6,800

I suggest to wait for sales and discounts in malls (or your favorite cell shop) to get these phones in even more lower prices. I even saw about Php 6000 (it was even an Acer with specs similar to my Samsung Galaxy 5, I just forgot the name :D). Its just a matter of time that Android will be affordable to everyone (Think of all you can do to it :D, what about rooting??? hehe). So what are you waiting for? Go grab your smartphone of your dreams.

    Monday, 18 July 2011

    Multi-Touch on Android

    Have you ever heard the word "pinch", "gestures", and "touch" (Yeah, the first word is doing something like this... OUCH!!!!!)? These terms are usually related to touch events on handsets (iPhone, Android, etc.).

    Touch Events are events that happens when you press, release, move, or any movement you do with the screen (Touching the screen is not limited to your fingers, as long as pressure is applied to any part of the screen). Implementing touch events on android is very simple. All you have to do is implement the OnTouchListener interface, register the implemented class to a certain view you want touch events to be handled (e.g. TextView), override the onTouch() method, and get some useful values of the MotionEvent parameter of the method (The useful ones are MotionEvent.getX(), MotionEvent.getY(), and MotionEvent.getAction()).

    Multi-touching, on the other hand, is a bit to complicated (Though its a bit similar to the simple single touch event like implementing the OnTouchListener, register it to a view, so on and so forth :D). The only difference is getting the values of each screen gesture (1 finger pressing, another for moving).

    Getting each touch event's position can be achieved by MotionEvent.getX(), but you must supply it with a argument of type int. This argument is so called pointer index. Sounds easy? No! You might be thinking that the pointer index is just the index of the touch event (0 for the first, 1 for the second, etc. ), which is not the case. This pointer index of ours is an index into internal arrays of the Motion Event that hold the coordinates of a specific event (or gesture). The real index of our specific touch event is the so called pointer identifier or pointer id. To get the pointer id, we will use the method MotionEvent.getPointerIdentifier() with the pointer index as our argument. This 2 terms must not be misunderstood as similar (maybe because of their spelling, probably :D). Just remember, [finger = pointer id. not pointer idx]. Now were starting to get on fire! Yeah!!!

    So how to get the pointer index if it is not the number of the finger I used? Hope you have practiced your bit masking tricks. To get the pointer index, you need to mask the MotionEvent.getAction() and MotionEvent.ACTION_POINTER_ID_MASK then shift the result with MotionEvent.ACTION_POINTER_ID_SHIFT.

    int pointerIndex = (MotionEvent.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;

    Next step is to get the event's action. To get the action of the event, all we need to do is mask the MotionEvent.getAction() and MotionEvent.ACTION_MASK.

    int action = MotionEvent.getAction() & MotionEvent.ACTION_MASK;

    With single touch events on Android, we only (or commonly) tackle MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, and MotionEvent.ACTION_UP. With multi-touch events, we will still use the same constants, but with 2 more constants. These are MotionEvent.ACTION_POINTER_DOWN and MotionEvent.ACTION_POINTER_UP.

    MotionEvent.ACTION_POINTER_DOWN event is similar to MotionEvent.ACTION_DOWN event. The only difference is that MotionEvent.ACTION_POINTER_DOWN happens when there are more than 1 touch event is fired (The first touch event produces a MotionEvent.ACTION_DOWN action).

    The same is to MotionEvent.ACTION_POINTER_UP and MotionEvent.ACTION_UP. The last touch event produces a MotionEvent.ACTION_UP and the rest are MotionEvent.ACTION_POINTER_UP. Note that the event that produces a MotionEvent.ACTION_UP action does not necessarily mean it is the same event that produces the MotionEvent.ACTION_DOWN action.

    To get the number of touch events (or fingers), you will use the MotionEvent.getPointerCount().

    The code below is a sample application that implements multi-touch support.

    public class MultiTouchTest 
    extends Activity 
    implements OnTouchListener
    StringBuilder builder = new StringBuilder();
    TextView textView;
    float[] x = new float[10];
    float[] y = new float[10];
    boolean[] touched = new boolean[10];

    private void updateTextView()
    for(int i = 0; i < 10; i++)
    builder.append(", ");
    builder.append(", ");

    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    textView = new TextView(this);
    textView.setText("Touch and drag, multiple fingers supported");

    public boolean onTouch(View view, MotionEvent event) {
    int action = event.getAction() & MotionEvent.ACTION_MASK;
    int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
    int pointerId = event.getPointerId(pointerIndex);

    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_POINTER_DOWN:
    touched[pointerId] = true;
    x[pointerId] = (int)event.getX(pointerIndex);
    y[pointerId] = (int)event.getY(pointerIndex);
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
    case MotionEvent.ACTION_CANCEL:
    touched[pointerId] = false;
    x[pointerId] = (int)event.getX(pointerIndex);
    y[pointerId] = (int)event.getY(pointerIndex);
    case MotionEvent.ACTION_MOVE:
    int pointerCount = event.getPointerCount();
    for(int i = 0; i < pointerCount; i++)
    pointerIndex = i;
    pointerId = event.getPointerId(pointerIndex);
    x[pointerId] = (int)event.getX(pointerIndex);
    y[pointerId] = (int)event.getY(pointerIndex);

    return true;


    You can download the file here.

    Getting the distance between 2 points using pythagorean theorem.
    What about pinching? You can implement pinching by getting the distance between 2 points. Use the distance to process pinching, like zooming by this value.

    Happy coding! :D

    Saturday, 16 July 2011

    Accelerometer Explained!

    Accelerometers brings more usability to Android devices. Your phone can be a pedometer, it can detect the acceleration of your car, and even playing your phone like Wii. Technically, an accelerometer is a device that reports the acceleration exerted by the gravity of our planet on a specific axes. Most Android phones have a three-axis accelerometer making our handsets more interesting. The acceleration is expressed in meters per second. When an axis points away from the center of the Earth, the maximum acceleration is applied to it. If an axis points toward the center of the Earth, we get a negative maximum acceleration. For example, if we hold our phone in portrait mode (image you hold it very straight and you dont have a shaky hands), the accelerometer will report an acceleration of 9.8 m/s (this is because of the gravity of the earth. Free falling objects will have an acceleration of 9.8 m/s towards) while the rest of its axes are 0 m/s.

    Android Phone with imaginary arrows representing the X and Y axis. Z axis' direction is in front of your phone.
    To better understand this explanation, lets create an application that displays the values of our accelerometer.

    First thing to do is to register a listener. The name of the listener is SensorEventListener. It has 2 methods to implement, onSensorChanged() and onAccuracyChanged(). onSensorChanged() is called whenever a new accelerometer event happens. The onAccuracyChanged() is called when the accuracy of our sensor changes.

    public class AccelerometerTest 
    extends Activity 
    implements SensorEventListener
    public void onAccuracyChanged(Sensor sensor, int accuracy) {


    public void onSensorChanged(SensorEvent event) {


    To register our listener, we need to check whether an accelerometer is installed on our Android device. We will be using a SensorManager class, which we will use to check for an accelerometer and register the listener to it. Here's the code to do all does things (place this code in your onCreate() method):

    SensorManager manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    if(manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0)
    //no accelerometer installed
    Sensor sensor = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
    if(manager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME))
    //cannot register sensor listener

    Your accelerometer is now ready. We will then display the values of our device's accelerometer. The SensorEvent parameter of our onSensorChanged() method has a field member named values which is an array. SensorEvent.values[0] returns the value of X axis, SensorEvent.values[1] returns the value of Y axis, and SensorEvent.values[2] returns the value of Z axis. Try holding your phone in portrait and you will get a positive number in the Y axis. For the X axis, try holding your phone in landscape, its right side facing to the sky. Also try facing your phone's screen to the sky to get a positive number in the Z axis.

    The full source code of this post is found here.

    Friday, 15 July 2011

    Rooting Android

    Hey! look at my rooted phone, it's so cool!

    I am using my phone to study Linux

    Rooting? What the hell is that by the way?

    Rooting your Android phone is the process of attaining a "root" access (Linux account that, by default, has all access to all commands and files on its system) within Android's Linux subsystem. You may not have noticed it, but manufacturers of your phone limits you from some of its capabilities (including the hardcore ones :D). Your phone might be able to support multi-touching capabilities, sharing your mobile data connection via USB or Bluetooth, or even make your phone a WIFI hotspot. Cool isn't it? There are even more capabilities to be discovered from your phone by rooting your Android device. Here are some things you can do with a rooted device:

    • Custom ROMS
    • Fancy Themes and UI
    • Performance Boosts
    • Unlock unavailable features
    • Hardware tweaks, overclocks, etc.
    • Root-only apps
    • and many more!
    Cool. Totally cool dude!

    Hey! Were not done yet. There's a catch when you try rooting your Android device. If you overdo things, like overclocking to the highest level, you might brick your phone. It will be rendered useless. No wonder why manufacturers limit our phone's capabilities :D. So be responsible when you are already in root.

    So how do we root Android-powered devices? 
    There are many ways, actually. Some of them are specific to a device. But there are apps that make your phone go root. Just a click or 2, your phone can now go ninja :D.

    I use Universal Androot which can be found here. There are others like Z4Root. Place the .apk file in your sdcard then click it to run the installer. Make sure that you enable installing non-market applications which can be found in Settings > Applications > Unknown sources. Then run Universal Androot or Z4Root. You will see a button that will make your device root-enabled. Click it and you will rule your device! (Check Universal Androot to see what I'm talking :D)

    This is the UI of Universal Androot

    Cool design of Z4Root

    Congratulations! Your phone is now rooted. Go to the Android Market for root-only applications and equip your device with powerful tools.

    Thursday, 14 July 2011

    Quick and Dirty Android Game Engine

    Hi guys! This is my first post of my first blog! :D And it will be about making a quick and dirty game framework from scratch. It took me months to research about android and making games on it (There were very few tutorials for game development on android and there are fewer game engines available for it). You can download the file that we will be making here.

    Let's start by creating a new android project. Supply the following information when prompted on creating a new android project:

    • Project Name: Dirty Game
    • Build Target: Android 3.1
    • Application Name: Dirty Game
    • Package Name: ind.crys.dirtyframework (or any package name of you choice)
    • Create Activity: DirtyActivity
    • Min SDK Version: 3

    Eclipse will now display a ready to use activity naming DirtyActivity. Lets start by implementing an OnTouchListener and override the onTouch() method.

    public class DirtyActivity 
    extends Activity 
    implements OnTouchListener

        public void onCreate(Bundle savedInstanceState) {

    public boolean onTouch(View view, MotionEvent event) 

    Next stop, we will need to make a way to hold some important values every time the players of our game will touch the screen and use those values on our game loop for further processing. We will be making a class inside the dirty activity naming "TouchEvent" with fields naming x, y, and eventType all with a type of int. The x and y fields are the X and Y coordinates of the touch event. The eventType is the type of action made by the user in the screen. We will then add 3 integer constants in this class naming TOUCH_DOWN, TOUCH_MOVE, and TOUCH_UP with values 0, 1, 2 respectively. This constants will be used in assigning the value of the eventType field (we cant use the MotionEvent.ACTION_XX constants because there are many of them, some can be confused with the other. Keeping things simple :D).

    class TouchEvent{
    int x;
    int y;
    int eventType;
    public static final int TOUCH_DOWN = 0;
    public static final int TOUCH_MOVE = 1;
    public static final int TOUCH_UP = 2;
    * @return the x
    public int getX() {
    return x;
    * @param x the x to set
    public void setX(int x) {
    this.x = x;
    * @return the y
    public int getY() {
    return y;
    * @param y the y to set
    public void setY(int y) {
    this.y = y;
    * @return the eventType
    public int getEventType() {
    return eventType;
    * @param eventType the eventType to set
    public void setEventType(int eventType) {
    this.eventType = eventType;
    public TouchEvent() {
    this.x = 0;
    this.y = 0;
    this.eventType = TOUCH_DOWN;

    public TouchEvent(int x, int y, int eventType) {
    this.x = x;
    this.y = y;
    this.eventType = eventType;

    We will add a field in our DirtyActivity class naming "lastTouchEvent" with the type TouchEvent. We will use this to get the touch input values and use it in our game loop. There are many other techniques on getting touch events (one of which is called Pooling) but lets keep this game engine simple. Every time the players of our game does something to the screen (touching it, swiping it, drooling on it) we will save the values of that event on the lastTouchEvent variable. Add to fields in our DirtyActivity naming scaleX and scaleY with the type float. We use this later on (particular to drawing things in the screen). Copy the line of code below replacing the old onTouch() method that we had last:

    public boolean onTouch(View view, MotionEvent event) {
    lastTouchEvent = new TouchEvent();
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_MOVE:
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:

    int newX = (int)(event.getX() * scaleX);
    int newY = (int)(event.getY() * scaleY);
    newX = (newX == 0) ? (int)event.getX() : newX;
    newY = (newY == 0) ? (int)event.getY() : newY;
    return true;

    The code above simply creates a new TouchEvent object and assign it to the lastTouchEvent variable. As you may have noticed, we assigned the X and Y coordinates of our touch event multiplied by scaleX/scaleY variable. It is because we will be drawing on a fixed sized canvas and because not all handsets (or even tablets) have the same screen size. We will then scale our canvas with the size of the handset. The scaleX and scaleY fields are the ratio of the handset's screen size and our canvas' size. By the time users touches the screen, the X and Y coordinates of the touch event will be in the exact position as that of the canvas, not the handsets screen. Later on, we will assign the scaleX/scaleY fields. 

    Next thing to do is to create a way to draw things in the screen. We will be extending the SurfaceView class and use it for drawing graphics (By the way, SurfaceView is a special view that we can use to make it draw on another thread). We will name this class as FastRenderView and it will inherit SurfaceView and implements Runnable interface. Copy the code below:

    class FastRenderView
    extends SurfaceView
    implements Runnable{
    Thread renderThread;
    SurfaceHolder holder;
    volatile boolean isRunning = false;
    public FastRenderView(Context context) {
    holder = this.getHolder();
    public void resume(){
    isRunning = true;
    renderThread = new Thread(this);
    public void pause(){
    isRunning = false;
    catch(InterruptedException e){
    public void run() {
    Rect dstRect = new Rect();
    long startTime = System.nanoTime();
    float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
    startTime = System.nanoTime();
    Canvas canvas = holder.lockCanvas();
    canvas.drawBitmap(DirtyActivity.this.frameBuffer, null, dstRect, null);

    We will use FastRenderView class as our game loop. On the run() method of this class, you will find that it calls 2 methods of our DirtyActivity naming update() and draw() both of which accepts a float value representing the delta time. We will be using these methods to update game logic and to draw objects in our game. The FastRenderView class also uses a Bitmap that is found in our DirtyActivity naming frameBuffer. The frameBuffer field will be our fixed sized canvas. The 2 methods of our FastRenderView class, naming pause and resume, are used when our activity is paused or resumed (pretty self explanatory isn't it?). 

    Were almost there! Copy the code before and place it in our DirtyActivity class:

    // Fields
    FastRenderView view;
    TouchEvent lastTouchEvent;
    Bitmap frameBuffer;
    Canvas graphics;
    Paint centralPainter;
    float scaleX;
    float scaleY;
    WakeLock wakeLock;

    public static int PREFFERED_WIDTH = 320;
    public static int PREFFERED_HEIGHT = 480;


    public void initialize(){

    public void update(float deltaTime){
    lastTouchEvent = null;

    public void draw(float deltaTime){

     * @return the lastTouchEvent
    public TouchEvent getLastTouchEvent() {
    return lastTouchEvent;

     * @return the graphics
    public Canvas getGraphics() {
    return graphics;

     * @return the centralPainter
    public Paint getCentralPainter() {
    return centralPainter;

    The view field is the instance of our FastRenderView that we will use. The frameBuffer field is our fixed sized canvas that we used to draw in our FastRenderView. The graphics field is the instance of our Canvas class that we will use to draw things in our game loop. The centralPainter field is an instance of Paint class that we will use on our graphics field (I guess 1 Paint class is enough, but you can make more instances of Paint class if you want to :D). We then declared a field named wakeLock with a type of WakeLock. We will use this for the heck of not turning off the lights of our screens while our users play our games. The methods below are getters that will be used to on our game engine (We will use getLastTouchEvent() to get the touch event values and use it in our update() method to further process. getGraphics() and getCentralPainter() methods will be used in our draw() method). PREFFERED_WIDTH and PREFFERED_HEIGHT is the width and height of our frameBuffer. Our game will be drawn out of these dimensions, scaled to the screen of our player's handsets. So if your game idea needs it to be in portrait orientation, change their values. Or if your game needs to be with 1024X768 screen dimensions (Wow!), change their values. We can change this the way you want your canvas will be drawn.

    Copy the code below to finalize everything.

    public void onCreate(Bundle savedInstanceState) {
    PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wakelock");
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    frameBuffer = Bitmap.createBitmap(PREFFERED_WIDTH, PREFFERED_HEIGHT, Config.RGB_565);
    graphics = new Canvas(frameBuffer);
    centralPainter = new Paint();
    view = new FastRenderView(this);
    scaleX = getWindowManager().getDefaultDisplay().getWidth() / PREFFERED_WIDTH;
    scaleY = getWindowManager().getDefaultDisplay().getHeight() / PREFFERED_HEIGHT;

    protected void onPause() {

    protected void onResume() {

    Most things here are android specific. PowerManager provides us the instance of our wakeLock field. Then we made our game full screen by calling requestWindowFeature() method and getWindow().setFlags() method. We then initialize our frameBuffer, graphics, and centralPainter fields. We then initialize our view field set our activity's view with this FastRenderView instance. 

    Thats it! To finalize everything, create an activity that extends our DirtyActivity class and override initialize(), update(), and draw() methods. Set this activity as your main activity in your Manifest file. Also set the screen orientation as portrait (or landscape, as long as it corresponds to your PREFFERED_WIDTH/PREFFERED_HEIGHT. You should use fixed orientation to not to confuse the players of our game)

    Lets try drawing something:

    public void draw(float deltaTime) {
    getGraphics().drawRGB(100, 149, 237);


    This will color the screen to my favorite color "Cornflower blue" (this color is the default background color of games made in XNA, a game framework for PC and XBOX using the language C#). You can do more in drawing with canvas like drawing lines, shapes, images (perfect for games) and many more. Your imagination is the limit. You can get some info in the official android Canvas documentation.

    Lets try processing input in our update() method:

    public void update(float deltaTime) {
    TouchEvent touchEvent = getLastTouchEvent();
    if(touchEvent != null){
    Log.i("Touch Event", touchEvent.toString());

    Everytime a touch event is made, LogCat will display the values of our TouchEvent. There's not much we can do in processing input because were limited with one TouchEvent and its not even supporting multi-touch functionality. Nevertheless, many games are still great with such limitations (Imagine all the games with point and click or point and drag input. Already imagined something?).

    This game engine does not do much, unlike other free/commercial android game engines out there. But I believe that making a great game or app is not about what engine we use. Its all in our ideas as a developer. 

    Happy coding! :D