I am in the process of writing a lexer for a text based game. A simplified example of what my code looks like this:
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")
With this code, I would like the player to enter something like: "Go West" and have a separate function take the substring "West", and then call the goWest() method for that Character.
asked Apr 26, 2015 at 18:28
electron1
971 gold badge1 silver badge10 bronze badges
1 Answer 1
You should use multiple if statements:
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)
Alternatively, you could alter your go function:
class Character:
def go(self, direction, location):
self.location = location
self.direction = direction
#call code based on direction
And go about the above as:
x = raw_input("What action would you like to take")
character.go(x.split()[-1].lower(), location)
You could use exec, but exec and eval are very dangerous.
Once you have functions goWest(), goEast(), goNorth(), and goSouth():
>>> func = "go"+x.split()[-1]+"()" #"goWest()"
>>> exec(func)
west
answered Apr 26, 2015 at 18:32
A.J. Uppal
19.3k7 gold badges48 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
electron1
Would there be an alternative method because my game could involve many more actions than just directions, and writing so many if statements would be difficult.
lang-py