我在生成一个随机对象时遇到了问题(仍然),在这个例子中是通过觅食发现的一种随机药草。下面是函数的代码:
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
return random.choice(herb_dict)
else: print"%s doesn't find anything useful." % self.name
以及dict块:
herb_dict = [
("Aloe Vera", Player().health == Player().health + 2),
("Cannabis", Player().state == 'high'),
("Ergot", Player().state == 'tripping')
]
抱歉,这些秘密的例子。Herb也是一个有三个参数的类:(self,name,effect)。你知道吗
调用collectPlants函数时,如何从dict生成一个随机的herb?你知道吗
random.choice
是一个方法,因此如果要调用它,需要使用()
而不是[]
。要访问列表中的元素,还需要使用[]
而不是()
。你知道吗对于您的情况,用满足您需要的
return random.choice(herb_dict)
替换return random.choice[herb_dict("")]
,它将在herb_dict
中随机返回一个元素。你知道吗但我认为你的方法的逻辑有问题。你知道吗
以上两条语句永远不会执行。你知道吗
你也可以用
if random.choice([0, 1]):
代替if random.randint(0,1) == 1:
。你知道吗你必须像下面那样使用随机选择需要一个序列来选择一个随机值。你知道吗
使用上面的结果,您将得到一个元组,并可以使用[index]访问元素,例如,要访问其中的第一个元素,请使用随机选择(药草药典)[0]
相关问题 更多 >
编程相关推荐