gpt4 book ai didi

python - 我收到此错误 --> TypeError : string indices must be integers

转载 作者:行者123 更新时间:2023-12-01 01:56:19 24 4
gpt4 key购买 nike

我正在尝试通过制作一个基于文本的角色扮演游戏来学习面向对象的编程,如下所示。与我的问题相关的部分是:

    def equipArmor(self):
for armor in self.armorsOwned:
select = 1
if self.armor == armor:
print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
else:
print(str(select) + ". " + str(armor["Name"]))
select += 1
armor_choice = input("Type the name of the armor you would like to equip\n")
for i in self.armorsOwned:
if armor_choice == i["Name"]:
if self.armor == i:
print("You already have that equipped")
else:
self.armor = i["Name"]
print("You equipped the {}".format(i["Name"]))
self.maxhp += i["Effect"]

和:

class Shop:

armors = {"BronzeArmor":{"Name": "Bronze armor",
"Cost": 30,
"Effect": 10},
"SilverArmor":{"Name": "Silver armor",
"Cost": 75,
"Effect": 20}}

以下是其余部分,以便您可以了解我的代码的上下文:

import time
import sys

class Player:

def __init__(self):
self.level = 1
self.exp = 0
self.gold = 0
self.maxhp = 20
self.hp = self.maxhp
self.attack = 1
self.weapon = ""
self.armor = ""
self.weaponsOwned = {}
self.armorsOwned = {}

def checkHp(self):
self.hp = max(0, min(self.hp, self.maxhp))

def deadCheck(self):
if self.hp == 0:
print("You died!")
sys.exit()

def equipArmor(self):
for armor in self.armorsOwned:
select = 1
if self.armor == armor:
print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
else:
print(str(select) + ". " + str(armor["Name"]))
select += 1
armor_choice = input("Type the name of the armor you would like to equip\n")
for i in self.armorsOwned:
if armor_choice == i["Name"]:
if self.armor == i:
print("You already have that equipped")
else:
self.armor = i["Name"]
print("You equipped the {}".format(i["Name"]))
self.maxhp += i["Effect"]

class Enemy:

def __init__(self, attack, maxhp, exp, gold):
self.exp = exp
self.gold = gold
self.maxhp = maxhp
self.hp = maxhp
self.attack = attack

def checkHp(self):
self.hp = max(0, min(self.hp, self.maxhp))

def enemyDeadCheck(self):
if self.hp == 0:
return True

class Shop:

armors = {"BronzeArmor":{"Name": "Bronze armor",
"Cost": 30,
"Effect": 10},
"SilverArmor":{"Name": "Silver armor",
"Cost": 75,
"Effect": 20}}

character = Player()
character.armorsOwned.update(Shop.armors["BronzeArmor"])
character.equipArmor()

我想做的是打印出我拥有的所有盔甲,如果已装备,则在其旁边打印“装备”,从输入中接收要装备的盔甲的名称,检查它是否已装备,然后装备如果没有装备的话。然而,标题中提到的错误阻止了我这样做。为什么会这样?什么是字符串索引?

最佳答案

循环字典(例如,for i in self.armorsOwned)返回的可迭代对象,而不是条目。所以 i 被设置为键字符串,而不是盔甲字典。

您想将字典上的所有循环转换为类似:

for i in self.armorsOwned.values():

关于python - 我收到此错误 --> TypeError : string indices must be integers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50145204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com