This is my first post sorry in advance for any etiquette missteps.
I am currently using pygame in Python to allow the user to customise what keys do what. The code below is my current condition but it does not solve the problem I'm having.
if keys[pygame.K_UP]:
What I actually want is something more like this:
if keys["pygame.customisable_key"]:
As far as I know the pygame preface has to be included because of the way I'm designing the class that import this one.
Thanks
The
pygame.K_constants are actually just numbers (integers) which you can put as the values into yourkeysdictionary.I'd define a dictionary with the actions (strings) as the dict keys and the pygame key constansts as the values, e.g.:
keys = {'move_left': pg.K_a, 'move_right': pg.K_d}.Then you can check in the event loop
if event.key == keys['move_left']:and handle that event as desired.To change a key, you first need to figure out to which action a new key should be assigned and when the next keyboard key gets pressed, insert the
event.keyattribute as the new value:keys[selected_action] = event.key.This is just a simplistic example which can still be improved, but it's complete and works correctly as far as I can see (Press Esc to toggle the assignment scene, press one of the previous keys to select an action and then another key to assign a new key to this action):