0

这与我今天早些时候提出的问题相连(“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

foundHerb 是随机选择。如何以简洁的方式将此项目添加到列表中(目前它打印草药名称,然后是“无”)并允许使用几种相同的草药?

这是草药类:

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')
]
4

2 回答 2

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')
]
  1. 这是错误的,=用于分配。==用于测试相等性。
  2. 您需要在这些元组的第二项中使用一个函数。
  3. 不要将第二项添加到列表中。像这样:

    self.herb.append(foundHerb[0])
    
于 2013-07-19T09:06:44.180 回答
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)
于 2013-07-19T09:13:51.597 回答