0

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?

1
  • You are working with a list, not an array. Commented Jan 26, 2017 at 18:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is correct, except I'm using Python 3.5.2. The range function literally returns a 'range' iterable object. So for those using 3+, use the list class (i.e. instead of range(16) use list(range(16))).
You're right (I use 2.7). Edited answer (using list comprehensions instead of list()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.