"List index out of range" 在对象的 3D 阵列上

"List index out of range" on 3D array of objects

我只是简单地尝试将一堆块存储在一堆块中。这是一个非常简单的体素世界。目前测试代码中有三个 class 级别(我打算玩 pickle 模块和序列化):世界,世界中的块,块中的块。

这是痕迹:

Traceback (most recent call last):  File "C:/Crayder/Scripts/pickle 
test/pickle1.py", line 27, in <module>    aWorld = world();  File 
"C:/Crayder/Scripts/pickle test/pickle1.py", line 25, in __init__    
self.chunks[cX][cY] = chunk(cX, cY);  File "C:/Crayder/Scripts/pickle 
test/pickle1.py", line 18, in __init__    self.blocks[bX][bY][bZ] = 
block((self.x * 16) + bX, (self.y * 16) + bY, bZ); IndexError: list 
index out of range

这是代码:

class block:
    def __init__(self, x, y, z, data = 0):
        self.x = x;
        self.y = y;
        self.z = z;
        self.data = data;

class chunk:
    def __init__(self, x, y):
        self.x = x;
        self.y = y;
        self.blocks = [];
        for bX in range(16):
            for bY in range(16):
                for bZ in range(64):
                    self.blocks[bX][bY][bZ] = block((self.x * 16) + bX, (self.y * 16) + bY, bZ);

class world:
    def __init__(self):
        self.chunks = [];
        for cX in range(16):
            for cY in range(16):
                self.chunks[cX][cY] = chunk(cX, cY);

aWorld = world();

print(aWorld.chunks[2][2].blocks[2][2][2]);

我做错了什么?

您正在创建空列表,然后尝试向其中分配。您收到的错误与

相同
l = [] 
l[0] = 'something'  # raises IndexError because len(l) == 0

您必须将元素追加到列表中:

l = []
l.append('something')

或预填充列表,以便您随后可以替换元素:

l = list(range(5))
l[4] = 'last element'

对于你的二维案例:

self.chunks = list(range(16))
for cX in range(16):
    self.chunks[cX] = list(range(16))
    for cY in range(16):
        self.chunks[cX][cY] = chunk(cX, cY)

您可以将其外推到三维情况。