为什么会出现密钥错误?

2024-09-28 01:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在列一个敌人的名单,他们对一个基于文本的游戏的损害,我得到了一个关键错误

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}$

Tags: 文本游戏outputrandomglobalnumprint名单
2条回答

你的字典,monsters,是由怪物的名字,而不是数字键。在

但是您传递的是一个数字num,作为一个键。在

解决这个问题的一种方法是使用list(name,level)元组(我只是猜测dict中的值是levels…),而不是dict。在

但更好的解决方案是使用random.choice而不是{}:

def spawnMonster():
    global output
    enemy = random.choice(list(monsters))
    print(enemy)
    output = "A " + monster + " comes out of the bushes."

或者,当然,把两者结合起来:

^{pr2}$

enemy, level = random.choice(monsters)

在我们讨论的时候,您的代码中还有几个其他错误:

  • 你把怪物的名字放在一个名为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())。在

因为这条线:

monsters[num]

尝试使用字典中不存在的密钥。Python字典不是PHP关联数组;字典中的值只能通过其关联键访问。在

创建一个怪物列表,然后使用random.choice()从中选择一个。在

相关问题 更多 >

    热门问题