使用Pygame开发2D射击游戏时出现IndexError: list index out of range错误
Pygame动画加载代码的IndexError修复方案
错误根源分析
你的代码存在两个核心问题,直接触发了IndexError: list index out of range:
- 缩进逻辑错误:第一个
for animation in animation_types:循环的代码块缩进错误,num_of_frames计算、帧加载循环以及self.animation_list.append(temp_list)都不在循环体内,导致实际只处理了最后一个动画类型(jump),动画列表填充完全不完整。 - 帧列表被错误清空:在加载每帧图片后立刻执行
temp_list = [],导致每添加一帧就清空列表,最终temp_list始终为空,self.animation_list里全是空列表,访问self.animation_list[self.action][self.frame_index]时自然会因为列表为空触发索引越界。
修复后的代码
import os import pygame # 假设scale、self.char_type、self.action、self.frame_index、x、y已提前定义 animation_types = ['idle', 'run', 'jump'] self.animation_list = [] # 先初始化动画总列表 for animation in animation_types: temp_list = [] frame_dir = f'img/{self.char_type}/{animation}' # 先检查目录是否存在,避免路径错误 if not os.path.isdir(frame_dir): print(f"警告:动画目录 {frame_dir} 不存在") self.animation_list.append(temp_list) continue num_of_frames = len(os.listdir(frame_dir)) for i in range(num_of_frames): img_path = f'{frame_dir}/{i}.png' # 检查单帧文件是否存在 if not os.path.exists(img_path): print(f"警告:帧文件 {img_path} 不存在") continue img = pygame.image.load(img_path) img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) temp_list.append(img) # 单类动画加载完成后,再将帧列表加入总列表 self.animation_list.append(temp_list) # 确保索引访问在合法范围内 if 0 <= self.action < len(self.animation_list): target_animation = self.animation_list[self.action] if target_animation and 0 <= self.frame_index < len(target_animation): self.image = target_animation[self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) else: print(f"错误:frame_index {self.frame_index} 超出当前动画帧范围") else: print(f"错误:action {self.action} 超出动画类型范围")
额外注意事项
- 确保
img/{self.char_type}/下存在idle、run、jump三个子目录,且每个目录内的图片严格按0.png、1.png...连续编号。 - 提前定义
self.animation_list,避免未初始化就使用。 - 添加路径检查可以快速定位文件缺失类的隐性问题,降低调试难度。
内容的提问来源于stack exchange,提问作者Foxxy.K
相关产品推荐
相关产品推荐

