Re: Games with Python
@5
I mean: it's not off topic, entirely.
Build a dict like this:
keys = {
"up arrow": { "on_down": "forward_start", "on_up": "forward_stop" },
# more entries here
}
Then, once you work out what the key is:
event_def = keys[key.name]
handler = event_def["on_down"] if key.down else event_def["on_up"]
handler = getattr(player, handler)
handler(key.down)
You pass whether the key is pressed or released to the event handler so you can use the same function for both, then, in the player:
class Player:
# stuff...
def forward_start(self, is_down): # walking forward. def forward_stop(self, is_down): # not walking forward
With the following obvious extensions, depending on your needs:
1. You can use the same function for both, recording whether the key was last down or up on the player.
2. You can add a shortcut key to the dict which takes precedence over the start/stop keys, which stands for both, and not have to write them out explicitly.
3. You can include modifier state to the function.
4. You can make the keys of the dict collections.namedtuple instead of strings, which lets you include modifiers in the trigger patterns.
5. You can store/load a file containing this.
6. You can wrap the entire thing in a convenience class which has helper methods for all this.
7. You can move to a more complex variant that uses a list instead of a dict, so that if you have 3 or 4 actions on the same key where only the modifiers are different, you can stop at the first one and do some additional tracking to deal with conflicts better (but then no audiogame really needs this one).
8. You can write some helper decorators that let classes advertise configurable key things they want to expose, with defaults, so that if the player object ever changes to something the player can control like a turret, you can have turret specific keys.
9. You can write a parser that handles strings like "ctrl + alt + a" and converts them to the dict, thn give the playere nice editable config files.
Obviously this varies depending on your library since how your library represents keys will be different from pygame to pyglet to wx to whatever. So don't expect to copy/paste this and have it work. But the above approach works in any dynamically typed language, and with some preprocessor magic and creativity you can do something similar in C/C++ if you want.
-- Audiogames-reflector mailing list Audiogames-reflector@sabahattin-gucukoglu.com https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector