1

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.

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.