Saturday, August 22, 2009

Simple Pygame Wrapper

I do a lot of prototyping. Simulations, user interfaces, algorithms etc. Often I'll use pygame to visualise the results, as it is a nice simple library.

Sometimes though, it's just a bit too low level. So I created SPW, which add a very light interface over the pygame drawing and blitting functions. This interface provides a canvas which handles scaling and translations, enabling you to easily scroll across a drawing, or zoom in and out. It also looks after dirty rectangle updates. This is what it looks like:

from spw import gui

with gui.Context() as canvas:
canvas.translate((400,300))
canvas.circle((0,0),50)
canvas.translate((0,150))
canvas.scale(0.5)
canvas.circle((0,0), 50)

The context manager tracks the dirty rectangles, and does a screen.update when it exits. I've put it on google code, and it can also be installed using easy_install.

6 comments:

ZeD said...

Just a little comment: why don't you return self on the canvas method?

so you can do something like

with gui.Context() as canvas:
canvas.translate((400,300)).circle((0,0),50)
.translate((0,150)).scale(0.5).circle((0,0), 50)

Simon Wittber said...

Zed, that is an awesome idea. I'm going to add it right away. Thanks!

illume said...

Very nice :)

Richard Jones said...

Here's another idea: shove all the instance methods for canvas into the locals() inside the context. I'm going to experiment with that for withgui (which I presume you've seen?)

Simon Wittber said...

Richard: Your withgui posts are part of the inspiration for this. Great idea. Thanks!

Richard Jones said...

I'd hope that the canvas in withgui could incorporate this sort of idea. I've always intended to have primitive drawing to complement the image and text drawing already done. Having built-in panning is also on the board, and adding scaling just sounds like a great idea. My main stumbling block is the GUI part - opengl is the obvious choice for the canvas part but then I need to get the rest of the gui going... fortunately people are working on guis in pyglet-space at the moment...

Popular Posts