我一直在Tkinter开发基于文本的游戏,我需要一种方法,以便在输入时提供更大的灵活性。基本上,我正在寻找的是如何编码:
if Input.get() == "look at" Item:
Item.look()
但是具有'项目的灵活性'作为一个具有子类的类,所有这些都可以被视为'。这是我对此细分的当前(非工作)代码:
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 = "{} is 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)
非常感谢任何帮助,
火焰
答案 0 :(得分:0)
您需要在输入和要调用的函数之间进行某种映射。您需要解析字符串,以便从输入字符串中提取对象,并使用解析结果来查找正确的对象或类。
例如,您可以使用正则表达式来解析字符串“look at X”,然后使用“X”作为字典的索引,以便知道要实例化的类。
这是一个简单的例子:
import re
class Headphones(object):
def look(self):
print("you are looking at headphones")
class Goggles(object):
def look(self):
print("you are looking at goggles")
class Unknown(object):
def look(self):
print("I don't know what you're looking at")
def check(input):
map = {
"goggles": Goggles,
"headphones": Headphones,
}
match = re.match(r'look at (.*)', input)
if match:
thing = match.group(1)
cls = map.get(thing, Unknown)
object = cls()
object.look()
for phrase in ("look at headphones",
"look at goggles",
"look at something else"):
check(phrase)
注意:这是解决问题的众多方法之一。关键是,你需要:
解析器可以是简单地将空格上的输入拆分并抓取最后一个单词,使用正则表达式,使用类似pyparsing之类的完整解析器。