每当我尝试运行代码时,都会遇到错误 IndexError: list index out of range
我正在尝试将 CSV 文件导入到我的代码中,以将岩石图像显示到我的项目的世界地图中。在我的 CSV 文件中,有一些值指示岩石在地图上的显示位置。这适用于另一个没有图像的文件,因此问题很可能出在岩石的图片中。我还尝试删除任何黑色空间,但不幸的是我不认为这是我的问题。我将在下面添加相关的屏幕截图。
相关代码
from csv import reader
from os import walk
import pygame
def import_csv_layout(path):
map = []
with open(path) as level_map:
layout = reader(level_map, delimiter=',')
for row in layout:
if not row or all(cell == '' for cell in row):
continue
map.append(list(row))
return map
def import_folder(path):
surface_list = []
for _,__,img_files in walk(path):
for image in img_files:
full_path = path + '/' + image
image_surf = pygame.image.load(full_path).convert_alpha()
surface_list.append(image_surf)
return surface_list
其他代码
def create_map(self):
layouts = {
'boundary': import_csv_layout("map/FloorBlock.csv"),
'rocks': import_csv_layout('map/Rocks.csv'),
# 'objects': import_csv_layout('map/Objects.csv'),
# 'houses': import_csv_layout('map/Houses.csv'),
# 'trees': import_csv_layout('map/Trees.csv'),
}
graphics = {
'rocks': import_folder("/graphics/Rocks"),
}
for style,layout in layouts.items():
for row_index, row in enumerate(layout):
for col_index, col in enumerate(row):
if col != '0':
x = col_index * TILESIZE
y = row_index * TILESIZE
# Create tiles
if style == 'rocks':
surf = graphics['objects'][int(col)]
Tile((x,y),[self.visible_sprites,self.obstacle_sprites],'object', surf)
我真的不知道如何直接链接我的csv文件,所以我会截图它的一部分
您已经对岩石图像进行了编号(0、2、3、5、6、231、234、293),并且您正在尝试获取与该编号相对应的图像(其中
col
是“0”或“234”) ”):
graphics['rocks'][int(col)]
问题是
graphics['rocks']
是import_folder("/graphics/Rocks")
的结果,这只是一个普通的列表。所以该表达式相当于:
import_folder("/graphics/Rocks")[234]
这个表达式试图获取第 235 个岩石图像(因为索引从 0 开始),但只有 8 个图像。
解决方案是更改
import_folder
以返回字典,其中岩石的数量是关键,图像是路径。假设您的图像以其编号命名(0.png
、234.png
等):
def import_folder(path):
surface_dict = {}
for _,__,img_files in walk(path):
for image in img_files:
name, ext = image.split('.')
full_path = path + '/' + image
image_surf = pygame.image.load(full_path).convert_alpha()
surface_dict[name].append(image_surf)
return surface_dict
或者,将 CSV 文件更改为岩石索引。因此,不要使用 234,而是使用 1:
0, 0, 0, 0, 0
0, 0, 1, 0, 0
0, 0, 1, 1, 0