Pygame平台游戏开发报错:'int'对象无'sprites'属性
问题:Pygame平台游戏报错AttributeError: 'int' object has no attribute 'sprites'
跟随教程用Pygame和Tiled开发马里奥类平台游戏,添加玩家目标显示功能时,运行到第150行self.goal.update(self.world_shift)时触发错误:AttributeError: 'int' object has no attribute 'sprites'
错误根源
- 初始化
self.goal时,只赋值了类pygame.sprite.GroupSingle,没加括号创建实例。后续调用self.goal.add(sprite)时,实际是调用了类的静态add方法,该方法返回整数,导致self.goal最终变成了整数类型,而非精灵组实例,自然没有sprites属性。 - 同样的问题也存在于
self.player = pygame.sprite.GroupSingle这行代码,虽暂时未报错,但后续使用必出问题。
修复方案
1. 修正精灵组初始化
在__init__方法中,给GroupSingle加上括号,创建实例:
self.player = pygame.sprite.GroupSingle() self.goal = pygame.sprite.GroupSingle()
2. 补充玩家逻辑(可选)
当前player_setup方法中val == '0'分支是空的,后续添加玩家精灵时需要补充对应逻辑,避免空分支无意义。
3. 修复create_tile_group潜在问题(可选)
- 移除全局变量
global sprite,改为局部定义,避免变量污染。 - 部分分支(如grass、crates)未直接将精灵添加到组,虽当前代码最后统一添加,但如果某个分支未生成精灵会报错,建议在每个分支内添加
sprite_group.add(sprite),或确保所有分支都生成有效精灵。
修正后的关键代码片段
初始化部分
def __init__(self, level_data, surface): super().__init__() self.display_surface = surface self.world_shift = 0 # player setup player_layout = import_csv_layout(level_data['player']) # 修正:创建GroupSingle实例 self.player = pygame.sprite.GroupSingle() self.goal = pygame.sprite.GroupSingle() self.player_setup(player_layout) # ... 其余代码不变
player_setup方法(补充玩家逻辑示例)
def player_setup(self, layout): for row_index, row in enumerate(layout): for col_index, val in enumerate(row): x = col_index * tile_size y = row_index * tile_size if val == '0': # 示例:添加玩家精灵 # player_sprite = Player(tile_size, x, y) # self.player.add(player_sprite) pass if val == '1': hat_surface = pygame.image.load('../graphics/character/hat.png').convert_alpha() sprite = StaticTile(tile_size, x, y, hat_surface) self.goal.add(sprite)
内容的提问来源于stack exchange,提问作者moron
相关产品推荐
相关产品推荐

