Monday 29 November 2010

Conway’s Game of Life (as an Android live wallpaper)

Having found Conway’s Game of Life to be a useful kata in C#, I thought I’d use it to explore some other technology. I’ve had an HTC Desire Android smartphone for a little while, so thought I’d see how hard it was to port something over.

I was hit by a number of gotchas while writing it – mostly down to using the API for the first time, and by not using Eclipse, instead using notepad++ and jdb to code and debug. jdb gave me a little trouble, but soon figured it out (on stackoverflow and here), realising that I had to make a socket connection to the emulator, and not the shared memory connection I seemed to be defaulting to.

I worked up a very simple app by just porting the core Life code I create in kata to Java, and then writing a minimal presenter over the top. The presenter comprises an Activity and an View; the Activity was just responsible for spinning up the backend engine – the View. The View is responsible both for keeping the evolution of the cells going, and displaying the current state. Dirty, but it worked.

Spot the glider ...In this case, and like many of the examples, there’s a message handler pump that keeps the model going. Messages to the renderer are posted delayed by the desired frame rate.

Converting the app to a live wallpaper sees the Activity transformed into a WallpaperService, which means we need to override the method onCreateEngine – in the case of a live wallpaper a specific Engine class actually drives the underlying model, and presents you with a SurfaceHolder on which to render the wallpaper.

As a  result, LifeEngine was reworked to inherit from Engine and render using a SurfaceHolder rather than a Canvas. The only real wrinkle there is that the Surface doesn’t get wiped between renders, so you need to wipe it yourself.

I wanted to pop up a dialog or other window when the user tapped the screen – that turned out to be not as straightforward as I’d assumed from a wallpaper. Handling the tap is easy enough, but bringing up a dialog less so.

Currently you can download the wallpaper here on the market, and the project should be up soon.

No comments: