Twisted + Pygame the Easy Way

I’ve put together a Python package called fibre. It provides helpers to make it easy to write asynchronous applications. It uses Twisted under the hood.

I’ve also made a package called fibre.ui. It adds user interface support using pygame.

One of my main aims has been code readability. See if you can figure out what this snippet from the demo program does:

The entry_point() function saves you from spelling out the __name__ == '__main__' incantation, and also initialises all the pygame and Twisted stuff. (If this is too magic for you, you can call run_application() which doesn’t do any stack magic.)

When yield is used, control is returned to the reactor until the given asynchronous function is finished (technically until the deferred fires, but for basic use of fibre you don’t have to know much about deferreds).

The code above comes with the following class definition for the menu. See if you can figure out what it means.

(Yes, there’s some magic in there behind the scenes. But I’ve almost convinced myself it’s worth it for the sake of readability.)

You may be wondering why colours are being specified as strings. You could also specify them as (R, G, B) or (R, G, B, A) tuples, but using the strings allows you to set up colour schemes. Here’s the relevant code:

By this stage I’ve shown you almost all of the code of the example, so I might as well show you the last little bit. This bit bounces a ball around until you press escape.

Hopefully this code is all clear enough that you can read through it and easily tell what it’s meant to do. After all, that was the aim of the exercise.

Is It Complete?

At time of writing, I can still think of billions of things that could be added to fibre.ui. So far it’s got enough stuff to write a ball bounce demo program in it, but I shall be improving it over time.

Can I Play With It?

The fibre module is licensed under version 2 of the GPL and is available on PyPI. Go forth and play!

This entry was posted in midlength and tagged , , , , . Bookmark the permalink.

Comments are closed.