I’d like to set up things like keyboard buttons in one script that would save everything to memory and call it in other scripts.
What I have tried and what worked was storing variables like integer and string.
you are storing the result of that into eKey…so it would only either be true or false that is getting stored. What are you trying to store - a mapping from BUTTON_1 to EKEY ?
I see. That would make sense from what it did.
What I’d like is to, for example, map any key in this case the EKEY to BUTTON_1.
I guess it would have to be a function that can be called in other scripts from memory.
from bge import events;
from bge.logic import keyboard;
KEYS={
'BUTTON_0':'EKEY',
'BUTTON_1':'WKEY',
};
def getActive(key):
return keyboard.inputs[key].active;
s="";
for key,value in KEYS.items():
s=s+f"{key}=lambda:"\
f"getActive(events.{value});\n";
exec(s);
if BUTTON_1():print(1);
Oof, nasty. Let me explain:
Write a dictionary with the format varname:keyid. varname is what you want to call the key, internally. keyid is some key name from bge.events
Write a function to fetch the state of a key.
For every key, generate a key-specific wrapper for that function. This means, basically, you assign a name to “calling this function with these args”.
exec the generated string. Yes. You can write python code as a string and then execute it. It’s an interpreted language, people.
Call the generated function whenever you want to get the state of the key. So it’s BUTTON_1() or whatever you name varname, with the parens, not without.
Here in the example I’m being lazy and assigning the function to a local. You could import script and then script.varname, and perhaps that’s what you should do rather than saving it to bge.logic.
But if you *must* save it to an already existing module, then
BTW my code here could be improved a whole lot, I didn’t give it much thought to be honest. With some retweaks I could enable key remaps and probably get rid of the exec altogether. Eh, ping me enough times and maybe I’ll do it.