Quantcast
Channel: scripters corner » Tutorial
Viewing all articles
Browse latest Browse all 2

Porting a game in pygame to Android

$
0
0

Today I want to introduce a way to port game written in 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. 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 it self.

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 on skip the part, where you 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 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 setup, 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 response with a 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 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

./android-sdk/tools/android
Android SDK Manager

Android SDK Manager

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 Adnroid API 8, which is needed to port pygame to Android. This will install the needed 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 to read through the breakout article and download the source code on github. 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 include 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 head 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.
try:
    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
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('break0ut')
    pygame.mouse.set_visible(0)

    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.init()
        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 maybe 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:
        clock.tick(60)

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

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 addition 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 question 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 question is concerned I have sticked 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 forget 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.

Breakout Game on an Android Emulator

Breakout Game on an Android Emulator

The post Porting a game in pygame to Android appeared first on scripters corner.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images