Lexigon: From iPhone to Android (Pt.1)

Our game Lexigon (Apple Store Link) was written using Apple’s XCode in objective-C and using the 2d game library cocos2d. Cocos2d is truely an excellent library, in short it gives you everything you need for game development, all the building blocks of a game. It is written in objective-C and best of all it is free. Head over to their web site to learn more.

I have had many requests to port Lexigon to Android, but knowing the differences between the two OSes I didn’t even look into the possibilities. This changed a few weeks ago. The Job-Which-Pays wanted me to investigate Android. Doing this I found some clever boffins had converted the cocos2d library from objective-C to C++. This port was is called cocos2d-x. Their aim was not just an Android port, but a cross-platfrom solution in general.

Android is based on Linux with the apps written in Java. They run within the Dalvik VM. (Google’s attempt to avoid the Java license.) There is, however, a way to run C code on android with the Android NDK (Native Development Kit). The app is still a Java based app but it loads a C++ library dynamically using JNI. This is how you can run cocos2d on Android.

When I first attempted porting the code from Objective-C to C++ using NDK, I tried doing this on Ubuntu with eclipse. Your milage may well vary, but for me after 5 days of trying to get eclipse to work with a Java and C project, I gave up. I just could not get this working. I could compile the C++ library on the command line of course, but without the IDE, I thought the porting would be too slow. My solution was to write the library under OSX. So I have two Xcode projects open side by side. The C++ one and the Objective-C one. As it turns out this is a pretty good setup. I can run the code on the iPhone simulator, then I just check the code out under Ubuntu and it compiles up without problem and can then run it on the Android device.

Here are the changes that you typically make when going from Objective-C to C++. First the header files which define your classes:

We can see that there are a lot of similarities between the two. For my code, I decided to keep the entire Obj-C name, so addWord:inPosition:flyingDirection: became addWordinPositionflyingDirection. We can also see the differences between the Objective-C syntax for calling methods and that for C++.

In Part2 of this tutorial I will cover more differences between Obj-C and C++ which I found during the port.