What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:
for event in pygame.event.get(): if event.type == KEYDOWN: if False: pass #make everything an elif elif rotating: pass elif event.key == K_q: elif event.key == K_e: elif event.key == K_LEFT: curpiece.shift(-1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece) elif event.key == K_RIGHT: curpiece.shift(1, 0) shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
(shortened). I don’t like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks?
You could create a dictionary where the keys are the input and the value is a function that handles the keypress:
Then changing the keys is a matter of modifying keys of the dictionary.