Reputation: 182
This is a code snippet for python mode of Processing. The purpose of this code is to update a variable when a key is pressed. Processing has a variable called keyPressed which is True if a key is pressed. The identity of the key that is pressed is saved as a string in the variable named key.
if keyPressed:
if key == "a":
a += 0.1
elif key == "s":
a -= 0.1
elif key == "q":
q += 1
elif key == "w":
q -= 1
elif key == "z":
z += 3
elif key == "x":
z -= 3
Is this just the best way to write this, or is there a better way? If not, what if there were 100 keys each with a different variable to tweak?
Upvotes: 1
Views: 80
Reputation: 77337
The challenge is that the if's are deciding which variable to update along with the value to add to the variable. Global variables can by accessed dynamically by name through the global()
namespace call. I noticed that one key updates a like-named variable and then the next key decrements that same variable by the same amount. So, that's 3 pieces of information per variable. You could put this into a list (or tuples) and then build a dictionary that tells you what action to take on each key press.
# var key, negated var key, value triplets
key_db = (("a", "s", .1), ("q", "w", 1), ("z", "x", 3))
key_index = {}
for var, nvar, val in key_db:
key_index[var] = (var, val)
key_index[nvar] = (var, -val)
if key_pressed:
try:
var, val = key_index[key]
globals()[var] = globals().get(var, 0) + val
except KeyError:
pass
Upvotes: 3
Reputation: 27485
There would be no way around using the first if statement but you can replace the second if statement with a dict.
And to differentiate adding and subtracting just negate the number.
ops = {'a': (a, 0.1),
's': (a, -0.1),
'q': (q, 1),
'w': (q, -1),
'z': (z, 3),
'x': (z, -3)}
if keyPressed:
var, amount = ops[key]
var += amount
Upvotes: 0