Saturday, June 23, 2012

Convert your keyboard into an Android game controller!

I have been gifted with a new android phone. It's the big G branded Galaxy Nexus. Its blazingly fast and awesome to use (especially after years of HTC Wildfire usage). Right from day one, i have been really addicted to this game called Temple Runner which wasn't compatible with my old phone.

The game is very straightforward to play and it involves only 4 different operations. Swipe up, left, right and down. Coming from a strong keyboard background, I was never 100% comfortable with touch interfaces as i was with keyboard. And these 4 operations sounded analogous to the accelerate, brake and turn operations while playing a racing game in the computer keyboard.

That got me thinking, is there a way to make the computer keyboard into a game controller for my Android phone? Turns out its fairly straightforward. In this post i'll explain exactly how to do that.

Ingredients
  • Android phone (obviously)
  • USB cable connected in debugging mode
  • Android SDK installed
  • Very very basic python english
There's a tool named monkeyrunner which enables us to send operations from the computer to the phone via a very simple Python API (monkeyrunner tool is a part of Android SDK). A sample code for a controller would look like this:

Code until line 7 is fairly straightforward to understand. The only thing that i would like to explain here is the device object. It is an object of the MonkeyDevice class. This class has all the API methods that you need to use in order to simulate the operations. For example, device.touch(100, 200, MonkeyDevice.DOWN_AND_UP) will simulate a touch event at co-ordinate 100, 200 (with the origin being top left). As simple as that!

You can find the detailed documentation of the monkey device class to know about other methods like drag, type, etc.

The full code which i used for playing Temple Run game is given below:


One point to note is that, the sys.stdin.read(1) line will read one character and wait for the enter key to be pressed. This could be annoying given that you are writing a game controller. In order to avoid the enter key press, if you are on linux run "stty raw" before running this script and if on windows use the getch function in msvcrt module.

-Vignesh