python 2.7 - Tkinter Input Substitutions -
i've been working on text based game in tkinter, , need way allow more flexibility input. basically, i'm looking how code:
if input.get() == "look at" item: item.look()
but flexibility of 'item' being class, subclasses, of can 'looked at'. current (non-working) code segment:
def check(): if output == "look at" item: item.look() else: pass class item(): def __init__(self, name, description, value, quantity): self.name = name self.description = description self.value = value def look(self): look.title = "{}".format(self.name) look.description = "{}".format(self.description) look.value = "{} worth {}.".format(self.name, self.value) details.insert(look.title) details.insert(look.description) details.insert(look.value) details.insert(look.quantity) class headphones(item): def __init__(self): super.__init__(name = "headphones", description = "a set of high quality white headphones.", value = 150)
any appreciated,
blaze
you need sort of mapping between input , functions want call. need parse string in order pull out object input string , use result of parsing proper object or class.
for example, use regular expression parse string "look @ x", , use "x" index dictionary in order know class instantiate.
here's simple example:
import re class headphones(object): def look(self): print("you looking @ headphones") class goggles(object): def look(self): print("you looking @ goggles") class unknown(object): def look(self): print("i don't know you're looking at") def check(input): map = { "goggles": goggles, "headphones": headphones, } match = re.match(r'look @ (.*)', input) if match: thing = match.group(1) cls = map.get(thing, unknown) object = cls() object.look() phrase in ("look @ headphones", "look @ goggles", "look @ else"): check(phrase)
note: 1 of many ways solve problem. point is, need to:
- write parser can pull out important parts input, and
- use result of parsing stage decide how process data
the parser can splitting input on spaces , grabbing last word, using regular expression, using full blown parser using pyparsing.