在尝试从文件创建自定义地图加载器时,我遇到以下问题:
"D:\Python 3.4\python.exe" "D:/Games in Python/Game1/game.py"
Traceback (most recent call last):
File "D:/Games in Python/Game1/game.py", line 60, in <module>
game = Game()
File "D:/Games in Python/Game1/game.py", line 4, in __init__
world = World()
File "D:/Games in Python/Game1/game.py", line 23, in __init__
self.load()
File "D:/Games in Python/Game1/game.py", line 54, in load
self.map_data[a][z][y][x] = self.tmp4[x]
IndexError: list index out of range
Process finished with exit code 1
我已经尝试通过打印列表的某些部分来自己调试,并逐步完成程序,但仍然没有成功。这是代码:
self.map = open("Data/Saves/test.txt" , "r")
self.map_dat = self.map.read()
self.map.close
self.tmp1 = self.map_dat.split("-")
self.map_data = [None] * 2
for a in range(0, 2):
self.tmp2 = self.tmp1[a].split(">")
self.map_data[a] = [None] * 4
for z in range(0, 4):
self.tmp3 = self.tmp2[z].split("\n")
self.map_data[a][z] = [None] * 100
for y in range(0, 100):
self.tmp4 = self.tmp3[y].split(",")
self.map_data[a][z][y] = [None] * 100
for x in range(0, 100):
self.map_data[a][z][y][x] = self.tmp4[x]
地图文件如下:
map_lvl0
>
map_lvl1
>
map_lvl2
>
map_lvl3
-
map_lvl0_properties
>
map_lvl1_properties
>
map_lvl2_properties
>
map_lvl3_properties
where map_lvl(0 to 3) a 100*100 grid of zeros seperated by ","
很抱歉给出了一个如此奇怪的地图文件说明,因为我无法在此处上传实际文件
我真的很感激这方面的任何帮助,任何使它更清洁,更短等的方法
答案 0 :(得分:0)
你的错误可能是网格外边缘的行,也就是一个tmp2
条目,比如“\ n实际数据\ n”,它不是以一行开头,因为空白没有被修剪关闭。或者可能是属性字段不存在于数值矩阵之外。
但是,这种地图格式可能不是存储数据的最佳方式。
就个人而言,我会使用二进制格式来提高效率或使用JSON文件(为了便于阅读,只需使用json
进行解析)。类似的东西:
[
{
"map_name" : "some name",
"map_prop2" : "some value",
...
"map_layout" : [
[0,...,0],
...,
[0,...,0]
]
},
...
]
如果你坚持使用当前格式,我会使用这样的函数( NOTE :你没有告诉我们属性的格式,所以我只是把它保存为单个字符串,在实际解决方案中解析它们:
# Returns a dictionairy
# lvls[map_name] -> { id : int, properties : string, grid : int[][] }
def read_map(filename):
lvls = {}
with open(filename, "r") as f:
lvls_data, lvls_props = f.read().split("-")
lvls_data = [ s.strip() for s in lvls_data.split(">") ]
lvls_props = [ s.strip() for s in lvls_props.split(">") ]
assert(len(lvls_data) == len(lvls_props))
for i in range(len(lvls_data)):
# I had no idea how to parse the properties, since I don't know the
# format. So I kept it plaintext, do actually parse them
data, properties = lvls_data[i], lvls_props[i]
grid = [ [ int(point) for point in line.split(",") ] for line in data.split("\n") ]
# assert all dimensions are in order
assert(len(grid) == 100)
assert(all(len(grid[i]) == 100 for i in range(100)))
lvls["map%i" % i] = { 'id' : i, 'properties': properties, 'grid' : grid}
return lvls
注意我无法对此进行正确测试,因此请谨慎使用