我目前正在做一个项目,在我的代码中,我试图获得树木。*。和山。^。在随机产生的第一棵树或山周围成群地产卵,然而,我无法弄清楚如何让树木和山脉在一个随机生成的点周围成群生成。有什么帮助吗?
grid = []
def draw_board():
row = 0
for i in range(0,625):
if grid[i] == 1:
print("..."),
elif grid[i] == 2:
print("..."),
elif grid[i] == 3:
print(".*."),
elif grid[i] == 4:
print(".^."),
elif grid[i] == 5:
print("[T]"),
else:
print("ERR"),
row = row + 1
if row == 25:
print ("\n")
row = 0
return
答案 0 :(得分:0)
您可以通过多种方式实现目标。
首先,你可以直接模拟这些组,即在网格上选择一个范围并用特定的数字填充它。
def generate_grid(size):
grid = [0] * size
right = 0
while right < size:
left = right
repeat = min(random.randint(1, 5), size - right) # *
right = left + repeat
grid[left:right] = [random.choice(figures)] * repeat
return grid
请注意,群组大小不需要均匀分布,您可以使用任何方便的分发,例如Poisson
其次,您可以使用Markov Chain。在这种情况下,组长度将隐含在Geometric distribution之后。这是代码:
def transition_matrix(A):
"""Ensures that each row of transition matrix sums to 1."""
copy = []
for i, row in enumerate(A):
total = sum(row)
copy.append([item / total for item in row])
return copy
def generate_grid(size):
# Transition matrix ``A`` defines the probability of
# changing from figure i to figure j for each pair
# of figures i and j. The grouping effect can be
# obtained by setting diagonal entries A[i][i] to
# larger values.
#
# You need to specify this manually.
A = transition_matrix([[5, 1],
[1, 5]]) # Assuming 2 figures.
grid = [random.choice(figures)]
for i in range(1, size):
current = grid[-1]
next = choice(figures, A[current])
grid.append(next)
return grid
在this StackOverflow回答中解释了choice
函数。