dan3008
dan3008

Reputation: 3

Pygame - customisable controls

I've been making games with pygame for a while, and have finally decided that I want to make customisable controls for my game, so that the player can change what buttons they use.

I've done this before (in Java) using a config file, but translating a string to a keypress is a slow and clunky proccess. I was wondering if anyone has any better ideas?

thanks

Daniel

Upvotes: 0

Views: 801

Answers (2)

jacwah
jacwah

Reputation: 2847

I would use two dicts. One maps keys to actions, like {"up": "move_up"}, and one maps actions to functions like {"move_up": player.move_up} (where player.move_up is a function). The key to action dict can be loaded from a config file, and the action to function can be hardcoded.

import pygame
from ConfigParser import SafeConfigParser

action2function = {
    "up": player.move_up,
    "down": player.move_down,
    "left": player.move_left,
    "right": player.move_right
}

config = SafeConfigParser()
config.read(CONFIG_DIRS)
key2action = config.items()

...
for event in pygame.event.get():
    if event.type == KEYDOWN:
        action2function[key2action[pygame.key.name(event.key)]]()
...

Upvotes: 1

Serial
Serial

Reputation: 8045

You could use a dict and assign each key to an action, and when the user changes the controls, just reassign the actions

example:

key_presses = {'a' : 'example()',
               'up' : 'rect.x +=1',
               'down' : 'rect.y -= 1'
               #etc

then you just get the event.key for each button press event like so:

#in your mainloop
if event.type == KEYDOWN:
    key = pygame.key.name(event.key) #returns name of key in string
    exec(keypresses[event.key])

event.key returns an int, then pygame.key.name() returns the name of the key as a string, so if you push the up button it executes the code for up that it gets from the dictionary

This is one way to do it, not sure if its the easiest, tell me if you have any questions

Upvotes: 1

Related Questions