我正在为基于文本的游戏编写词法分析器。我的代码如下所示的简化示例:
class Character:
def goWest(self, location):
self.location == location.getWest() #getWest() would be defined in the location class
x = raw_input("What action would you like to take")
使用此代码,我希望播放器输入类似于:“Go West”并使用单独的函数获取子字符串“West”,然后为该Character调用goWest()方法。
答案 0 :(得分:1)
您应该使用多个if
语句:
x = raw_input("What action would you like to take")
direction = x.split()[-1].lower()
if direction == "west":
character.goWest(location)
elif direction == "east":
character.goEast(location)
elif direction == "north":
character.goNorth(location)
else:
character.goSouth(location)
或者,您可以更改go
功能:
class Character:
def go(self, direction, location):
self.location = location
self.direction = direction
#call code based on direction
以上所述为:
x = raw_input("What action would you like to take")
character.go(x.split()[-1].lower(), location)
您可以使用exec
,但exec
和eval
非常危险。
一旦你有了goWest()
,goEast()
,goNorth()
和goSouth()
的功能:
>>> func = "go"+x.split()[-1]+"()" #"goWest()"
>>> exec(func)
west