Jump to content

  • Log In with Google      Sign In   
  • Create Account


From Python to Android

By Janosch Henze | Published Oct 29 2014 05:26 AM in Mobile Development
Peer Reviewed by (Dave Hunt, jbadams, Michael Tanczos)

python android pygame pgs4a

I have published this article to my blog before, but because it is not so frequently visited and I did not find much advice for this subject I am writing the same article down here to share with everyone.

This article is about porting a game written in python with pygame to Android. To do so we will use the pygame subset for Android, which can be obtained here. The pygame subset for android has ported a subset of the pygame architecture to the Android architecture. Hence it allows us to easily program games in python and port them to an Android application. This article will explain how to do so by using the breakout game, programmed by myself and obtainable here: Attached File  break0ut.zip   39.08KB   233 downloads

In the end we will have a breakout game on our Android device which can be controlled by swipe gestures or by tilting the android device itself.

If you want to rebuild what we will build during this article you will need the following programs:
  • A Java Development Kit e.g. via Oracle or OpenJDK
  • Python 2.7 and pygame obtainable here and here
  • Device Drivers for your Android device, if you are using Windows and a little help for Linux here
  • pygame subset for Android (PGS4A), obtainable here
These programs are more or less needed if you want to run the breakout game itself and then later port it to your Android device. If you plan to skip this part and simply run the game on your local PC, the pygame library is not needed. The whole porting and programming is just one more click apart.

Setting everything up

The first three parts just need to be installed, either via a package management system if you are using Linux or by downloading and installing them if you are using Windows. PGS4A just needs to be extracted in a folder of your choice. As far as my project setup is concerned this looks like the following and can be viewed on github:

./pgs4a/ directly containg all PGS4A stuff
./pgs4a/breakout/ containing all the python source code and our main.py
./pgs4a/breakout/data/ containing all images and so on for our game

This structure needs to be like this because PGS4A will only work this way. Now mostly everything is set up, except PGS4A - we will start with this. First you should test if everything is up and running for PGS4A by running:

cd pgs4a
./android.py test

This should return green text stating All systems go! This basically means that we met all prerequesits. After this we need to install the corresponding Android SDK which can be done by executing

./android.py installsdk

This should start the installation of the needed Android SDK. During this installation you are asked to accept the TOS of the Android SDK and if you would like to create an application signing key, which is needed if you want to publish your application on the Play store. You should answer both questions with yes. The key is needed later on for some signing purposes and the installation process. But be warned if you want to sell the application in the Play store you will need to recreate a key, because the key created during this process uses no password. If you have finished successfully you will be rewarded with It looks like you're ready to start packaging games.

Important: At this point you must make sure that you actually installed an SDK! You may get an error or a warning that the filter android-8 is not accepted. If you received such an error you need to manually install the Android 8 sdk. This can be done by running


Attached Image: androidSDKManager.png

Now the Android SDK manager should come up. You may need to update Tools before you actually see the same content as in the window above from there you can now install the Android API 8, which is needed to port pygame to Android. This will install the required API manually, which is needed because PGS4A has long not been updated. After this we are nearly ready to start porting our breakout pygame to Android.

Adding Android to breakout

In this part we are going to actually add the android device stuff to our game. For this purpose I would recommend you read through and download the source code. Now you should be capable of running the code within your python environment and be able to play the breakout game. If not make sure you have done everything right regarding the setup of your python and pygame.

All modifications, and we do not have much modifications, are performed in the main.py, which includes the main function of our game. The modification includes importing the Android stack of PGS4A, initializing the Android stack, map Android-specific keys and adding some Android-specific stuff. Afterwards we should be capable of playing without further modifications to our game.

Importing the Android package should be done below our standard imports in the main file. Hence we need to change the header with the imports to something which looks like this:

import pygame, sys, os, random
from pygame.locals import * 
from breakout.data.Ball import Ball
from breakout.data.Bar import Bar
from breakout.data.Block import Block

# Import the android module. If we can't import it, set it to None - this
# lets us test it, and check to see if we want android-specific behavior.
    import android
except ImportError:
    android = None

Now we have imported the Android-specific commands and are able to ask if we can access them or not via the android variable. The next step would be to initialize the Android environment and map some keys, we do this after we initialized pygame and set some parameters:

def main():
        """this function is called when the program starts.
				it initializes everything it needs, then runs in
				a loop until the function returns."""
# Initialize Everything
        width = 800
        height = 600
        screen = pygame.display.set_mode((width, height))

        background = pygame.Surface(screen.get_size())
        background = background.convert()
        background.fill((0, 0, 0))

        # Map the back button to the escape key.
        if android:
                android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

At the bottom of the above code we checked if the Android package was loaded, if this is the case we initialize the android subsystem and map the back key of our Android device to the Escape key. So if we wanted to add a menu to our application which is normally called with the Escape key this would open the menu. In this particular example of breakout the Escape key will exit the game.

Next we have to react to some Android-specific stuff, which is needed in each game. The game may be put into a pause mode, e.g. when the application is switched or the user tries to go back to the home screen. To react to this kind of behavior we have to add the specific code to our game loop:

# main game loop
        while 1:

                # Android-specific:
                if android:
                        if android.check_pause():

This would wait for a resume of our application if our game application was set in the pause mode. Due to the checks for the android variable we are capable of playing the same game on the PC as well as on our Android device. If you want to start the PC version simply run the main.py and you are ready to go. With these last additions to our main source code, we are now capable of porting our breakout game to an Android Application and develop on the PC using our standard setup.

The porting process

Now we have reached the point were we want to put everything we have created so far to our Android device. To do so we need to configure our setup, which is easily done running the following command:

./android.py configure breakout

Make sure that the breakout folder exists before you execute the command otherwise you will get some errors. After you have executed this command you will be asked several questions including the name of the application and the package. As far as the package is concerned make sure not to use any special characters including -, _ and so on, otherwise you will get errors later in the process. As far as the rest of the questions are concerned I have stuck to the default answers. After you have finished you should be able to see a file called .android.json in the breakout folder, which should look like this:

{"layout": "internal", "orientation": "landscape", "package": "net.sc.breakout", "include_pil": false, "name": "breakout", "icon_name": "breakout", "version": "0.1", "permissions": ["INTERNET", "VIBRATE"], "include_sqlite": false, "numeric_version": "1"}

The next and last step before we can play our game on our Android device is the compilation and the installation of the apk on our phone. Both is handled by the following command line:

./android.py build breakout release install

Before you execute the command make sure you have created an assets folder. If you have not the execution will fail and you are not capable of compiling the application. I guess the creator of the PGS4A forgot or did not implement stuff to create folders. Also as I mentioned before PGS4A is an old application and therefore may not work very well.

If you have done everything correctly you should be able to play the game on your android device or the emulator you have connected or started. It should look very similar to the picture below. You should now be capable of porting any game created with pygame to android.

Attached Image: breakoutOnAndroid.png


GDOL (Gamedev.net Open License)


Thanks a lot, it was a nice article. :) . I'll try the PGS4A soon..

Cool, using Pygame games to port it on android. It seems like a dream became true.

Note: Please offer only positive, constructive comments - we are looking to promote a positive atmosphere where collaboration is valued above all else.