Pygame on Android (Intermediate)

Android is an open source smartphone operating system initially developed by Google. Most of the Android apps are written in the Java programming language and run on a Java-based virtual machine. Fortunately, we can create Pygame games for Android phones. This is not a trivial matter and we will only cover the bare basics.

Getting ready

We will install the Pygame Subset For Android (PGS4A). You will need to have the JDK, Python 2.7 or a later version installed before we start. Download the appropriate software for your operating system from http://pygame.renpy.org/dl.

To install the necessary software, we will require an Internet connection and quite a lot of room on your hard drive. If you don't have a couple of gigabytes to spare, you may need to make more space. We can install the Android SDK and other software we will need such as Apache Ant by running the following command:

android.py installsdk

This will start a wizard that will guide you through the installation. It's safe to accept all the default options during the installation procedure, but you do have to generate a key. Unless you are really serious about creating apps, you don't have to worry how secure this key is.

How to do it...

We will create a simple game that prints "Hello World From Android!" and call it mygame.

  1. Setting up the game: Create a directory with the same name as the name of the game and place a main.py file in there with the following contents:
    import pygame
    
    # 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
    
    # Event constant.
    TIMEREVENT = pygame.USEREVENT
    
    # The FPS the game runs at.
    FPS = 30
    
    def main():
        pygame.init()
    
        # Set the screen size.
        screen = pygame.display.set_mode((480, 800))
    
        # Map the back button to the escape key.
        if android:
            android.init()
            android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    
        # Use a timer to control FPS.
        pygame.time.set_timer(TIMEREVENT, 1000 / FPS)
    
        while True:
            ev = pygame.event.wait()
    
            # Android-specific:
            if android:
                if android.check_pause():
                    android.wait_for_resume()
    
            # Draw the screen based on the timer.
            if ev.type == TIMEREVENT:
                screen.fill((255, 255, 255))
                font = pygame.font.Font('freesansbold.ttf', 32)
                rendered = font.render('Hello From Android!', 0, (255, 100, 100))
                screen.blit(rendered, (100, 100))
                pygame.display.flip()
    
            # When the user hits back, ESCAPE is sent. Handle it and
            # end the game.
            elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
                break
    
    # This isn't run on Android.
    if __name__ == "__main__":
        main()

    This is basically the code from the PGS4A website changed to print a welcome message. A more thorough explanation will be given at the end of the recipe.

  2. Configuring the game: We can configure the game with the following command:
    android.py configure mygame
    

    We will accept all the defaults and set the storage setting to internal.

  3. Building, installing, and running the game: Android is essentially a Java framework, so there is a lot of compiling involved. This is a bit different than in the Python world. Since this game is simple, building will not take that long. First we will start the emulator—this is an application that mimics the behavior of an actual phone. Find the android executable that is part of the Android SDK. Launch it and choose Tools | Manage AVDs… | New… in the GUI application that opens. Create an Android Virtual Device (AVD) and give it a name. Hit the Launch… button. A phone emulator will start. If it is locked, you can unlock it by pressing F2.

    We can now build and install the game with the command:

    android.py build mygame release install
    

How it works...

The relevant functions used in this code are described as follows:

Function

Description

android.init()

This function initializes Android

android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

This function maps the Android back button to the Pygame escape button

pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

This function fires events at specified time intervals given in milliseconds

android.check_pause()

This function checks for a pause request

android.wait_for_resume()

This function puts the game in sleep mode

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset