Wednesday, April 20, 2011

Clever Python Hacks Part I - Keymapping

Keymapping was complicated stuff in Magecrawl. See here for the XML reader(LoadKeyMappings() and HandleKeystroke). It was powerful stuff, using reflection, XML and such. However, I just got 80% of that in a four liner today:

def load_key_mapping():
    globalDict = {}
    exec(open("KeyMapping").read(), globalDict)
    return globalDict["KeyMapping"]

This function loads the given file as a python script and executes it, then sucks out the KeyMapping dictionary. The KeyMapping script looks like this:

import pygame

KeyMapping = \
{
    pygame.K_UP : 'Up',
    pygame.K_DOWN : 'Down',
    pygame.K_RIGHT : 'Right',
    pygame.K_LEFT : 'Left',
}

I get a simple dictionary of button presses to string, and I can switch off those later. The only concern I have is people sharing KeyMapping files and people doing stupid things in them. However, right now I'm now that concerned, as this is stupidly simple and works great.

2 comments:

alex dante said...

I think this is equivalent and preferable:

def load_key_mapping():
..import keymapping
..return dict(
....KeyMapping=keymapping.KeyMapping
..)

You could turn your 'keymapping' file into a module or package called 'globals' instead and then just refer to globals.KeyMapping too :)

donblas said...

You are probably right, I'm still enough of a python noob to not have the best idea of what to divide into modules.