我在列一个敌人的名单,他们对一个基于文本的游戏的损害,我得到了一个关键错误
import random
monsters = {"Goblin":1, "Troll":3, "Bear":2, "Giant Spider": 1, "Bandit":1,"Wolf":1,"Homeless Man":1, "Goblin Chief":3}
monsterNum = 0
for monster in monsters:
monsterNum += 1
def spawnMonster():
global output
num = random.randint(0, monsterNum)
print(num)
global enemy
enemy = monsters[num]
print(enemy)
output = "A " + monster + " comes out of the bushes."
spawnMonster()
print(output)
输出:
^{pr2}$
你的字典,
monsters
,是由怪物的名字,而不是数字键。在但是您传递的是一个数字
num
,作为一个键。在解决这个问题的一种方法是使用
list
(name,level)元组(我只是猜测dict中的值是levels…),而不是dict
。在但更好的解决方案是使用}:
random.choice
而不是{或者,当然,把两者结合起来:
^{pr2}$在我们讨论的时候,您的代码中还有几个其他错误:
enemy
的变量中,但是你试图使用一个名为monster
的变量。在randint(0, monsterNum)
给你一个从0到monsterNum
的数字,包括monsterNum
。但这将是1太多,而且,即使你有一个列表,你也会得到一个IndexError
每次它选择最后一个数字。索引使用randrange
,而不是randint
。在monsterNum = 0
然后for monster in monsters: monsterNum += 1
工作时,只做monsterNum = len(monsters)
就简单多了。在global output
作为从函数返回信息的一种方式,但是更好的方法是仅使用return output
,并让外部代码执行print(spawnMonster())
。在因为这条线:
尝试使用字典中不存在的密钥。Python字典不是PHP关联数组;字典中的值只能通过其关联键访问。在
创建一个怪物列表,然后使用
random.choice()
从中选择一个。在相关问题 更多 >
编程相关推荐