我目前正在做一个学习python的小项目。该项目创建一个随机森林,然后设置森林着火,以刺激森林火灾。所以我设法用一个函数创建了这个林子。森林只是一个0和1的数组。0代表水,1代表一棵树。
所以现在我真的被困在如何用我的阵列来激发森林大火上了。我知道如何引发和蔓延火灾背后的逻辑,但我不知道该如何将其写成代码。
逻辑是:
所以我很难写出循环,把1替换成2,然后用3来代替,这样它就从一棵树扩散到另一棵树。
我成功地编写了一个函数来创建随机林。问题是把森林放火焚烧。我试着写了一些for-循环,但我真的不知道该如何处理这个问题。
#Define parameters for createForest Function. Sets the parameters for the forest too.
width = int(5)
height = int(5)
density = float(0.7) # probability of spawning a tree
forest = [[]]
#Making a random forest
def createForest(width, height, density):
forest = np.random.choice(2, size=(width, height), p=[(1-density), density])
return forest
print(createForest(width, height, density))
forest = createForest(width, height, density) # updates forest into the list这将以随机顺序打印出0和1的数组:
[[1 0 1 1 1]
[1 1 1 1 1]
[0 0 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]发布于 2019-03-25 13:37:01
不是为你解决整个问题,而是带走所有的乐趣,但我相信缺失的部分是np.where
import numpy as np
forest = np.random.randint(0, 2, (10,10))
x, y = np.where(forest == 1)
print(x) # up down
print(y) # left right该函数在矩阵中输出x,y坐标,用于在相邻单元格(坐标)中执行测试和操作。
您可以这样组合这些坐标对来迭代它们:
coord_pairs = np.vstack((x,y))
coord_pairs.shape # (2, 48)
coord_pairs[0,:] # x
coord_pairs[1,:] # y
for k in range(coord_pairs.shape[1]):
print(f"x:{coord_pairs[0,k]}, y:{coord_pairs[1,k]}")state management as explained in this other answer on your question也是必需的。
发布于 2019-03-25 13:38:43
您正在实现一个元胞自动机,为了模拟这个过程,您需要为您的工作创建一个数组的副本。基本算法的工作方式如下:
new_state = state.copy()
for i in range(height):
for j in range(width):
new_state[i,j] = calculate_new_cell(state, i, j)
state = new_state( calculate_new_cell(state, i, j)函数依赖于元胞自动机的规则。)
https://stackoverflow.com/questions/55338811
复制相似问题