This is the second part of the series “Snake with different Guis” in which I will describe the port of the Snake game to the Android platform.
The first part was Java Swing: Snake with different Guis”.
This is the first time I developed an Android application, so there are still some weaknesses in the code, but all in all it works.
General Structure of Android game
I kept the general structure of the program as described in the first part “Java Swing: Snake with different Guis”. The only difference is that the AndroidGameController now actually does run the main game loop in its own so that the updating of the view works (over a Handler) – otherwise the execution of the logic would block the updating of the view.
Here is a UML class diagram of the general structure including the new android classes as well as the old Swing once.
Gui with Android
I decided to use a GridView containing TextViews to display the game field. This turned out to be a suboptimal decision. I later found out that it is not meant to be repeatedly updated and is quite slow. The game is still playable, but in the future I will use a SurfaceView for this kind of thing.
Input
There are two ways to provide input to the game: The cursor and the Touchscreen.
– Cursor
The input to the cursor can be received with a simple OnKeyListener. The last input is saved in a field and retrieved by the GameController when needed (so only the last key pressed in one game turn will be applied to the game).
– Touchscreen
It turned out that the gathering of input via the touch screen is a little more complicated. The different text view do not cover the whole game field, so if the player would touch between them, the input would not be registered when using OnItemClickListener.
I then used a OnTouchListener for the whole gridview and translated the absolute position of the touch event. This does work, but seems to be not the optimal solution. I will leave it like this anyways because I expect that most users will provide input via the cursor.
Source Code
The source code (eclipse project) for Snake with Swing as well as Snake with Android is attached to the download.
Screenshots
model-view-controller uml class diagram – android
Download Android Snake Game (Source Code attached)