我不喜欢 if/elif 语句看起来有多难看。switch/case 语句也好不到哪里去。我发现字典更容易阅读。现在我知道如果每个键绑定到不同的功能时如何处理它,这很容易。但这需要 8 个不同的移动函数(moveNE、moveN、moveNW 等)。所以我想要一个简单的 move_object 函数,它将方向作为参数。但是,我在让这段代码正常工作时遇到了问题,而且我不确定我做错了什么。这是有问题的代码。
一、字典:
self.keybindings = {ord("h"): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"North"}},
ord('j'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"South"}},
ord('g'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"East"}},
ord('k'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"West"}},
ord('y'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"NorthWest"}},
ord('u'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"NorthEast"}},
ord('b'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"SouthWest"}},
ord('n'): {"function":self.move_object,
"args":{"thing":self.things[0], "direction":"SouthEast"}},
ord('l'): {"function":self.look, "args":{"thing":self.things[0],}},
ord('q'): {"function":self.save_game,
"args":{"placeholder":0}}}
现在,move_object 函数:
def move_object(self, thing, direction):
"""I chose to let the Game class handle redraws instead of objects.
I did this because it will make it easier should I ever attempt to rewrite
this with libtcod, pygcurses, or even some sort of browser-based thing.
Display is cleanly separated from obects and map data.
Objects use the variable name "thing" to avoid namespace collision."""
curx = keywords[thing].x
cury = keywords[thing].y
newy = keywords[thing].y + directions[keywords[direction]][0]
newx = thing.x + directions[keywords[direction]][1]
if not self.is_blocked(newx, newy):
logging.info("Not blocked")
keywords[thing].x = newx
keywords[thing].y = newy
最后,应该调用 move_object 函数的代码:
c = self.main.getch()
try:
self.keybindings[c]["function"](self.keybindings[c]["args"])
except KeyError:
pass
键绑定在 Game Class init函数中定义,最后的代码块发生在 Game.main_loop()
我已经阅读了几次教程,但我无法弄清楚我做错了什么。我认为我在这里所拥有的会将 args 字典作为 **keywords 传递给 move_object() 函数,但它给了我一个参数错误(预期 2 个参数,收到 1 个)。