我正在为一个游戏生成洞穴。这些洞穴是由细胞自动机建立的50x50矩阵,其中0(紫色)是墙,1(黄色)是空地(玩家可以移动的地方)。下面是我输出的一个例子
我指出了我对红圈的问题。墙壁上有一些 "洞",玩家无法到达。我试图填补这些洞,但我不能。基本上我想把被0包围的1变成0。
我试着用洪水填充这个方法来实现这个目标。
首先,我数了一下从起点x,y开始用泛函填充画了多少个单元。如果这个计数小于16而大于1,那么我就实际绘制单元格。
for x in range(0, WIDTH - 1):
for y in range(0, HEIGHT - 1):
number_cells_paint = floodfill_count(cellmap, x, y, number_cells_paint)
if 16 > len(number_cells_paint) > 1:
floodfill(cellmap, x, y)
number_cells_paint = []
数目_单元格_绘制 是一个数组,在这个数组中,我将我访问的每一个单元格附加到了 溢出量_计数. 这是我认为递归算法里面的计数方式,可能是我的错误所在。
这就是floodfill_count。
def floodfill_count(cellmap, x, y, number_cells_paint):
cellmap_aux = cellmap
if len(number_cells_paint) > 16:
return number_cells_paint
if cellmap_aux[x, y] == 1:
cellmap_aux[x, y] = 0
number_cells_paint.append(cellmap[x, y])
if x > 0 and cellmap[x - 1, y] == 1:
floodfill_count(cellmap_aux, x - 1, y, number_cells_paint)
if x < WIDTH - 1 and cellmap[x + 1, y] == 1:
floodfill_count(cellmap_aux, x + 1, y, number_cells_paint)
if y > 0 and cellmap[x, y - 1] == 1:
floodfill_count(cellmap_aux, x, y - 1, number_cells_paint)
if y < HEIGHT - 1 and cellmap[x, y + 1] == 1:
floodfill_count(cellmap_aux, x, y + 1, number_cells_paint)
if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y + 1] == 1:
floodfill_count(cellmap_aux, x + 1, y + 1, number_cells_paint)
if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y + 1] == 1:
floodfill_count(cellmap_aux, x - 1, y + 1, number_cells_paint)
if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y - 1] == 1:
floodfill_count(cellmap_aux, x + 1, y - 1, number_cells_paint)
if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y - 1] == 1:
floodfill_count(cellmap_aux, x - 1, y - 1, number_cells_paint)
return number_cells_paint
和 floodfill:
def floodfill(cellmap, x, y):
if cellmap[x, y] == 1:
cellmap[x, y] = 0
if x > 0 and cellmap[x - 1, y] == 1:
floodfill(cellmap, x - 1, y)
if x < WIDTH - 1 and cellmap[x + 1, y] == 1:
floodfill(cellmap, x + 1, y)
if y > 0 and cellmap[x, y - 1] == 1:
floodfill(cellmap, x, y - 1)
if y < HEIGHT - 1 and cellmap[x, y + 1] == 1:
floodfill(cellmap, x, y + 1)
if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y + 1] == 1:
floodfill(cellmap, x + 1, y + 1)
if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y + 1] == 1:
floodfill(cellmap, x - 1, y + 1)
if x < WIDTH - 1 and y < HEIGHT - 1 and cellmap[x + 1, y - 1] == 1:
floodfill(cellmap, x + 1, y - 1)
if x > 0 and y < HEIGHT - 1 and cellmap[x - 1, y - 1] == 1:
floodfill(cellmap, x - 1, y - 1)
return cellmap
这个 floodfill 的实现是可行的,我以前也试过,所以我的问题出在 floodfill_count 上。
在这段代码中,我有 此最终输出
问题是在 cellmap_aux = cellmap
这行代码。Python 将列表分配为一个引用,所以对 cellmap_aux
的变化。cellmap
(所以 floodfill_count
绘制所有的领域)。) cellmap_aux = cellmap.copy()
应使用。