[英]how do i resolve this error: TypeError: 'type' object is not subscriptable"
am creating a shooter game and i observed something.我正在创建一个射击游戏,我观察到了一些东西。 everything in my code was working well until i created a dictionary and tried to access it through its key in a function but instead i got this error: TypeError: 'type' object is not subscriptable.
我的代码中的所有内容都运行良好,直到我创建了一个字典并尝试通过它在 function 中的键来访问它,但我得到了这个错误:TypeError: 'type' object is not subscriptable。 below is where i declared the dictionary, called it in a class, and where i created an instance of it from a class respectively
下面是我声明字典的地方,在 class 中调用它,我分别从 class 创建了它的实例
grenade_img = pygame.image.load("img/icons/grenade.png").convert_alpha()
# pick up boxes
health_box_img = pygame.image.load("img/icons/health_box.png").convert_alpha()
ammo_box_img = pygame.image.load("img/icons/ammo_box.png").convert_alpha()
grenade_box_img = pygame.image.load("img/icons/grenade_box.png").convert_alpha()
# name_dt = type(name)
item_boxes = {
"health": health_box_img,
"ammo": ammo_box_img,
"grenade": grenade_img,
}
class ItemBox(pygame.sprite.Sprite):
def __init__(self, item_type, x, y):
pygame.sprite.Sprite.__init__(self)
self.item_type = item_type
self.image = item_boxes[self.item_type]
self.rect = self.image.get_rect()
self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height()))
# create item boxes
item_box = ItemBox["health", 100, 300]
item_box_group.add(item_box)
item_box = ItemBox["ammo", 400, 300]
item_box_group.add(item_box)
item_box = ItemBox["grenade", 500, 300]
item_box_group.add(item_box)```
please can anyone show me what else to do to get result请谁能告诉我还有什么要做才能得到结果
The error is because you use square brackets []
instead of normal brackets ()
creating ItemBox
objects.该错误是因为您使用方括号
[]
而不是普通括号()
创建ItemBox
对象。 You can replace them and everything should work fine.您可以更换它们,一切正常。 The code from 2nd frame is
第二帧的代码是
item_box = ItemBox["health", 100, 300]
item_box_group.add(item_box)
item_box = ItemBox["ammo", 400, 300]
item_box_group.add(item_box)
item_box = ItemBox["grenade", 500, 300]
item_box_group.add(item_box)
after replacing.更换后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.