You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

射击游戏开发中TypeError: 'type' object is not subscriptable错误的解决方法咨询

解决TypeError: 'type' object is not subscriptable错误

问题根源

嘿,我一眼就找到问题所在了——你创建ItemBox实例的方式用错符号啦!

在Python里,方括号[]是用来做下标访问的(比如取字典的键值、列表元素),而类本身属于type类型的对象,它不支持下标操作。要创建类的实例,你得用**圆括号()**来调用类的构造函数__init__才行,这就是你触发这个错误的核心原因。

具体修改步骤

你只需要把创建ItemBox实例的代码里的方括号全部改成圆括号就可以解决问题:

错误代码片段:

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)

修正后的代码片段:

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)

完整修正后的代码参考

为了方便你直接使用,这里贴出所有相关的修正后代码(顺便补充了必要的初始化检查):

import pygame

# 假设你已经定义了TILE_SIZE常量
TILE_SIZE = 64

grenade_img = pygame.image.load("img/icons/grenade.png").convert_alpha()
# 拾取箱子资源
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()

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()))

# 务必先初始化精灵组
item_box_group = pygame.sprite.Group()

# 创建物品箱子(已修正实例创建方式)
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)

额外小提示

记得确认item_box_group已经正确初始化为pygame.sprite.Group(),不然添加实例时会触发新的报错哦。

内容的提问来源于stack exchange,提问作者Kenny Okoye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:37:35