这与我今天早些时候提出的问题相联系("List" Object Not Callable, Syntax Error for Text-Based RPG)。现在我的困境在于将草药添加到玩家的药草清单中。
self.herb = []
是起始药草清单。函数collectPlants:
def collectPlants(self):
if self.state == 'normal':
print"%s spends an hour looking for medicinal plants." % self.name
if random.choice([0,1]):
foundHerb = random.choice(herb_dict)
print "You find some %s." % foundHerb[0]
self.herb.append(foundHerb)
print foundHerb
else: print"%s doesn't find anything useful." % self.name
findHerb是随机选择。如何以整洁的方式将此项目添加到列表中(目前它打印药草名称,然后“无”)并允许使用几种相同的草药?
这是草药类:
class herb:
def __init__(self, name, effect):
self.name = name
self.effect = effect
草药样本清单(警告:不成熟):
herb_dict = [
("Aloe Vera", Player().health = Player().health + 2),
("Cannabis", Player().state = 'high'),
("Ergot", Player().state = 'tripping')
]
答案 0 :(得分:3)
使用列表。
self.herb = []
foundHerb = 'something'
self.herb.append(foundHerb)
self.herb.append('another thing')
self.herb.append('more stuff')
print 'You have: ' + ', '.join(self.herb)
# You have: something, another thing, more stuff
编辑:我在其他一个问题中找到了您foundHerb
的代码(请在此问题中发布!),即:
foundHerb = random.choice(herb_dict)
当我查看herb_dict
时:
herb_dict = [
("Aloe Vera", Player().health == Player().health + 2),
("Cannabis", Player().state == 'high'),
("Ergot", Player().state == 'tripping')
]
=
进行分配。 ==
用于测试相等性。不要将第二项添加到列表中。像这样:
self.herb.append(foundHerb[0])
答案 1 :(得分:0)
在您的函数中,想一想如果random.choice([0,1])
为0
会发生什么。它不会运行if
块,因此不会选择草药。也许在你的功能中,你可以return False
说没有找到草药。然后你可以这样做:
self.herb = []
myherb = collectPlants() # This will either contain a herb or False
if myherb: # If myherb is a plant (and it isn't False)
self.herb.append(myherb)