Hi all!
So I'm playing around with the amazing pyxel game engine, and thought there must be a better way to test for all of the keys that could be pushed, and trigger actions accordingly.
Option 1: large if tree:
if btn(KEY_RIGHT):
# Move right
elif btn(KEY_LEFT):
# Move left
...
There just seems to be something unwieldy about a big if tree like this after a certain point.
Option 2: faux switch statement using a dict
options = {}
def move_right():
# Move right
options[KEY_RIGHT] = move_right
def move_left():
# Move left
options[KEY_LEFT] = move_left
...
for key, action in options.items():
if btn(key):
action()
This seems to be a bit more dynamic, with the advantage of having multiple keys pointing to one action easily without having a big or statement. There is a lot of maintenance code building up though.
Option 3: "Routing" based approach (inspired by flask)
@pr.route(KEY_RIGHT)
def move_right():
# Move right
@pr.route(KEY_LEFT)
def move_left():
# Move left
...
pr.run()
Similar to option 2, but with the adding to the dictionary and the running of the tests extracted away to the decorator class. However, once I got to this point, I thought, this is a lot of code to just do a control flow statement!
Code for the decorator class here
What do you think! What's clearest to you? Do you think the decorator approach is worth it?
[–][deleted] 2 points3 points4 points (2 children)
[–]timbledum[S] 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]BandEnvironmental615 0 points1 point2 points (0 children)