Reputation: 155
I'm just simply trying to store a bunch of blocks in a bunch of chunks. It's for a very simple voxel world. There are three class levels at the moment in the test code (I was going to play around with the pickle module and serializing): the world, chunks in the world, and blocks in the chunks.
This is the trace:
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
And here is the code:
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]);
What am I doing wrong here?
Upvotes: 0
Views: 659
Reputation: 3319
You are creating empty lists and then trying to assign into them. The error you're getting is the same as
l = []
l[0] = 'something' # raises IndexError because len(l) == 0
You have to either append elements to the list:
l = []
l.append('something')
or prepopulate the lists so that you can then replace the elements:
l = list(range(5))
l[4] = 'last element'
For your two dimensional case:
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)
which you can extrapolate to the three dimensional case.
Upvotes: 1