【发布时间】:2019-10-23 11:19:05
【问题描述】:
我正在制作一个小行星生成器,它可以创建一个bools 的二维数组。
生成器采用int 参数size,它应该确定二维数组中有多少True 单元格。
如何保证输出数组中没有空洞,并且单元格数量正确为True?
我看到了Randomly Generating Clusters in a 2d Array 的问题,但我想不出办法将它应用到我的用例中,因为我需要知道必须生成的图块数量。
在下面的代码中,我随机放置瓦片,然后使用元胞自动机进行平滑并确保没有孔,但保持正确数量的True 单元是问题,特别是因为取出随机的True 单元满足正确的尺寸可能会产生孔。
def create_shape(size, seed):
# init rng with seed
rng = random.Random(seed)
# initial grid values empty and full mass left
# make the grid size by size so any shape could fit
grid = [[False for x in range(size)] for y in range(size)]
mass_remaining = size
# guarantee the center is something
center = size // 2
grid[center][center] = True
mass_remaining -= 1 # remember to reduce available mass
# generate random values
for x in range(size):
for y in range(size):
# skip the already filled in center
if x == y == center:
continue
# assign random value
value = bool(rng.randint(0, 1))
grid[y][x] = value
# remember to reduce mass
if value:
mass_remaining -= 1
# smoothen things out with cellular automata neighbor checking
for x in range(size):
for y in range(size):
# skip the center
if x == y == center:
continue
# get neighbors
# set neighbors is the count of neighbors set to True
set_neighbors = 0
for i in range(-1, 2):
for j in range(-1, 2):
# skip counting self
if i == j == 0:
continue
nx, ny = x + i, y + j
if 0 <= nx < size and 0 <= ny < size:
# only get in-range cells
if grid[ny][nx]:
set_neighbors += 1
# more than 3 -> become True, less than 3 -> become False
if set_neighbors > 3:
grid[y][x] = True
mass_remaining -= 1
elif set_neighbors < 3:
grid[y][x] = False
mass_remaining += 1
else:
# otherwise leave it the same
pass
# find out how well the mass is staying "in-budget"
print(mass_remaining)
return grid
该函数经常prints 输出一系列不同的剩余质量数量,例如,在“债务”中具有-14 或具有额外的42。如果函数正常工作,我希望输出为0。
比如这样的输出……
create_shape(8) ->
[ 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 0, 0,
0, 1, 1, 1, 0, 0,
0, 1, 1, 1, 1, 0,
0, 1, 1, 1, 1, 0 ]
... 是实心的,但有太多设置的图块。
【问题讨论】:
标签: python multidimensional-array procedural-generation cellular-automata