python菱形公式_Python菱形正方形算法的实现
我尝试创建一个基于this javascript的菱形正方形算法,因为它是可读的,对我来说也是有意义的。我有一些问题,但我似乎无法解决。在
运行代码时,所需的输出是填充2D数组每个位置的随机值,该值与初始数组初始化不同。我遇到的问题是,结果2D数组没有被完全填充,当网格大小增加到3以上时,我得到一个IndexError: list index out of range错误。在
代码如下:class DiamondSquare:
def __init__(self, size, roughness):
self.size = (size ** 2) + 1
self.max = self.size - 1
self.roughness = roughness
self.grid = self.make_grid(self.size)
self.divide(self.max)
print(self.grid)
def divide(self, size):
x = size / 2
y = size / 2
half = size / 2
scale = self.roughness * size
if (half < 1):
return
# Squares
for y in range(half, self.max, size):
for x in range(half, self.max, size):
s_scale = random.uniform(0, 1) * scale * 2 - scale
self.square(x, y, half, s_scale)
# Diamonds
for y in range(0, self.max, half):
for x in range((y + half) % size, self.max, size):
d_scale = random.uniform(0, 1) * scale * 2 - scale
self.diamond(x, y, half, d_scale)
self.divide(size / 2)
def square(self, x, y, size, scale):
"""
TL TR
X
BL BR
"""
tl = self.grid[x - size][y - size]
tr = self.grid[x + size][y - size]
bl = self.grid[x + size][y + size]
br = self.grid[x - size][y + size]
average = ((tl + tr + bl + br) / 4) + scale
self.grid[x][y] = average
def diamond(self, x, y, size, scale):
"""
T
L X R
B
"""
t = self.grid[x][y - size]
r = self.grid[x + size][y]
b = self.grid[x][y + size]
l = self.grid[x - size][y + size]
average = ((t + r + b + l) / 4) + scale
self.grid[x][y] = average
def make_grid(self, size):
grid = []
for y in range(size):
temp = []
for x in range(size):
temp.append(-1)
grid.append(temp)
grid[0][0] = self.max
grid[self.max][0] = self.max / 2
grid[self.max][self.max] = 0
grid[0][self.max] = self.max / 2
return grid
def get_grid(self):
return self.grid
当尝试将size变量(在init中)增加到大于2的值时,我得到以下回溯:
^{pr2}$
老实说,我不知道为什么会发生这种事,我根本就搞不懂。我使用以下代码生成此错误:a = DiamondSquare(x, 0.7)
其中x是大于2的任何整数,第二个参数是粗糙度。在
同样关于网格错误,尝试从钻石方块除法(),生成以下内容:[[4, 1.0649105908291359, 1.234026481506731, 0.07818244918327344, 2],
[0.43855022217756057, 0.4659935454877355, 1.283183468707215, 0.28019876872734906, -1],
[-0.4946413746345607, -1.1327574166276582, 0.45804405178511276, -1.4905717022572778, -1],
[-1.4175095415414622, -0.660055583070249, -0.8017056243549873, -0.18216161649389495, -1],
[2, -1, -1, -1, 0]]
在-1的地方,应该有其他的随机数和网格的其他部分一样。-1组成了底部和右侧的中点。我相信这与我的钻石循环有关,但我不确定我错在哪里。在
我实现这个网格,我使用以下代码:a = DiamondSquare(2, 0.7)
其中第一个参数是尺寸,第二个参数是粗糙度。在
请帮我解决上述问题好吗?提前谢谢你!在
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
