Tuesday, November 5, 2013

Pygame Subset for Android Sprite Optimization with RenderUpdates


In order to get 2D map games written in python working faster on low-end Android phones, I experimented with optimizations. I purposely selected a complex background image in order to stress the application.

The first set of huge gains came from using the Surface.convert_alpha() method to optimize the images. This was easy and resulted in significant performance gains.

The trickier part was to update only the sections of the screen that had changed since the last cycle.

I decided to use sprites for this since many of the optimization examples I've seen use sprites.  Instead of using pygame.sprite.Group, I used pygame.sprite.RenderUpdates.  This is basically the same as the sprite group, but it as the enhanced ability to track the changed areas of the screen.

The images in the group are drawn to the screen with the standard sprite.Group.draw(SCREEN) method.  The cool little addition is the RenderUpdates.clear(SCREEN, background) method which clears the sprite by blitting a piece of the background over it.  Nice.

The final section is to update the display with a list of the rectangles, pygame.display.update(rectlist).

That's the main things to change.  I experimented with not ticking the pygame.time.Clock under android.   I'm not sure if it makes a difference, but the application appeared to me to run slower on android when I used the clock tick.

This is the first time that I've used this bit of code to pause the android device when the user hits things like the home button on the phone.


I was pretty happy that my alpha transparency worked with the sprite group.


I also experimented with different ways to optimize the events. However, I couldn't find anything useful.

Here's the full code.

2 comments:

  1. I am having some trouble loading images in a project I am working on. How is the file structure supposed to be. It runs fine on PC but not on android. Thank you.

    ReplyDelete
  2. standard PNG files work. Lots of full examples here: https://github.com/codetricity/pychildren

    ReplyDelete