pythonmatplotlibvoxels

Appending a Boolean array


Ok, I'm new to programming and this might be something everybody knows...

I'm creating a game, and one of the features I'm intending to add is a 3D room map that I plan on generating with code. The problem I'm facing is that I need to append a Boolean array or whatever it's called without knowing how many elements it's going to contain. Here is the test code and the problem highlighted.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import random as rd

x,y,z = np.indices((8,8,8))

Lines = []

#Random straight lines
for i in range(4):
    rd.choice([
    Lines.append((x == rd.randint(0,8)) & (y == rd.randint(0,8))),
    Lines.append((y == rd.randint(0,8)) & (z == rd.randint(0,8))),
    Lines.append((x == rd.randint(0,8)) & (z == rd.randint(0,8))),
    ])
cols.append('r')

Voxels = Lines[0] | Lines[1] | Lines[2] | Lines[3] #I need to generate this 
#not Hard code it
colors = np.empty(Voxels.shape, dtype=object)
for i in range(len(Lines)):
    colors[Lines[i]]= 'r'

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(Voxels, facecolors = colors, edgecolor='c')

plt.show()

Any help would be appreciated.


Solution

  • What you are trying to do with your original line would be equal to :

    Voxels = Lines[0] | Lines[1]
    Voxels = Voxels | Lines[2]
    Voxels = Voxels | Lines[3]
    

    As the operations are done from left to right. Using parenthesis, it would look like :

    Voxels = (((Lines[0] | Lines[1]) | Lines[2]) | Lines[3])
    

    So, instead of doing...

    Voxels = Lines[0] | Lines[1] | Lines[2] | Lines[3]
    

    You should do...

    Voxels = Lines[0]
    for line in Lines[1:4]:
        Voxels = Voxels | line
    

    And if you want to do more than the 4 first Lines, you could just do for line in Lines[1:]. I did this at the beginning, and it bugged me not to get the same result as you're original hardcoded example.