2 entries tagged picky and python

Picky Picky Game: Tidying up the Python code

Having got the first working version of the Picky Picky Game, I have naturally now pulled it apart again. I decided that now it is in a state where it makes sense to try to package up a version for Adrian to try installing, I better think about getting the module and package names right, since it will be harder to change them later.

I have reorganized my Python classes in to their own package pdc (designed to prevent name collisions with WWW-oriented packages by other people). I also changed some of the file names—so that ‘import httputils’ becomes ‘from pdc import www’.

There is now a proper unit-test suite for the www module (which has functions like urlDecode, urlResolve, and xmlencode). This is easier to do for this odule than the others, which tend to involve creating scads of HTML text which will be hard to check for errors. For the URL-manipulating functions, the unit tests turned out to be invaluable—there are a lot of corner cases that I only sorted out because I had tests for all of them.

Now with BMP support

To make it easier to create pictures for the Picky Picky Game, I have added code to automatically convert Microsoft Windows Bitmap (.bmp) files into PNGs.

This is straightforward because I already was using PIL to check the dimensions of the images. Converting to PNG (if the format is one PIL knows) is pretty simple:

permittedTypes = ['image/png', 'image/jpeg', 'image/pjpeg', 'image/gif']
if not imt in permittedTypes:
    buf = StringIO.StringIO()
    im.save(buf, 'PNG')
    data = buf.getvalue()
    logger.log(slog.WARNING, 'Converted your image from %s to image/png' % imt,
	       'This may have lead to a slight loss of image quality.')
    imt = 'image/png'

The above goes in the sequence of checks on uploaded images (after the check for width × height, but before the check for number of bytes). I think I spent longer creating a BMP image to test it on than I did writing the new code!

The advantage of BMP support is that, if you have Microsoft Windows, then you definitely have Microsoft Paint installed. So long as you know about Start menu → Programs → Accessories → Paint, and the Image → Attributes menu item, you can create panels for Picky Picky Game.