附加一个布尔数组

Appending a Boolean array

好的,我是编程新手,这可能是每个人都知道的...

我正在创建一个游戏,我打算添加的功能之一是我计划使用代码生成的 3D 房间地图。我面临的问题是我需要附加一个布尔数组或它所调用的任何东西,而不知道它将包含多少元素。 这是测试代码和突出显示的问题。

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()

如有任何帮助,我们将不胜感激。

您尝试对原始行执行的操作将等于:

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

因为操作是从左到右进行的。使用括号,它看起来像:

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

所以,与其做...

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

你应该做...

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

如果你想做的不仅仅是前 4 行,你可以只做 for line in Lines[1:]。我在一开始就这样做了,这让我很烦恼,因为我没有得到与你原来的硬编码示例相同的结果。

好的,最初我通过按照列表的顺序单独绘制线条来规避这个问题。

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import random as rd
W = 15
H = 15
D = 15
NoPlane = 5
NoLine = 10

Lines = []
Planes = []
Cubes = []
Spheres = []

x,y,z = np.indices((W,H,D))
#Random straight lines| Lines only run up and down
for i in range(NoLine):
    Lines.append(
        (x == rd.randint(0,W)) & (y == rd.randint(0,D)) & (z >= 
    rd.randint(0,int(H/2))) & (z <= rd.randint(int(H/2),D))
        )


#random Levels| Levels run horosontaly
for i in range(NoPlane):
    Planes.append((z == rd.randint(0,H)) & (x >= rd.randint(0,int(W/2))) & 
    (z <= rd.randint(int(W/2),W)))

fig = plt.figure()
ax = fig.gca(projection='3d')
#Draw each thing individualy instead of all at once
for i in range(len(Lines)):
    ax.voxels(Lines[i], facecolors = 'r', edgecolor='c')
for i in range(len(Planes)):
    ax.voxels(Planes[i], facecolors = 'b', edgecolor='r')

ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()

但是这个方法太暴力了