我正在为基于文本的游戏编写词法分析器。我的代码的简化示例如下:
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”,然后为该角色调用goWest()方法。
您应该使用多个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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句