菱形方块算法Python

2024-09-26 22:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python创建一个DS算法,但是我相信我在正确填充矩阵时遇到了问题。我的其他指数都是0。我的代码如下,后面提供了一个示例输出。我用这个来生成地形数据。从其他例子来看,我认为我的指数应该更接近,而不是从(20,-8)跳起来

import random
class DiamondSq:

def __init__(self, k):
    self.size = (2 ** k) + 1
    self.max = self.size - 1
    self.r = 1
    self.grid = self.createGrid(self.size)
    self.diamondSquareAlgorithm(self.max)

def diamondSquareAlgorithm(self, size):

    x = size / 2
    y = size / 2
    halfStep = size / 2
    scale = self.r * size

    if (half < 1):
        return None

    # Squares
    for y in range(halfStep, self.max, size):
        for x in range(halfStep, self.max, size):
            s_scale = random.uniform(0, 1) * scale * 2 - scale
            self.squareStep(x, y, halfStep, s_scale)

    # Diamonds
    for y in range(0, self.max, halfStep):
        for x in range((y + halfStep) % size, self.max, size):
            d_scale = random.uniform(0, 1) * scale * 2 - scale
            self.diamondStep(x, y, halfStep, d_scale)

    self.diamondSquareAlgorithm(size / 2)

def squareStep(self, x, y, size, scale):

    topLeft = self.grid[x - size][y - size]
    topRight = self.grid[x + size][y - size]
    botLeft = self.grid[x + size][y + size]
    botRight = self.grid[x - size][y + size]

    average = ((topLeft + topRight + botLeft + botRight) / 4)
    self.grid[x][y] = average + scale

def diamondStep(self, x, y, size, scale):

    top = self.grid[x][y - size]
    right = self.grid[x + size][y]
    bottom = self.grid[x][y + size]
    left = self.grid[x - size][y + size]

    average = ((top + right + bottom + left) / 4)
    self.grid[x][y] = average + scale

def createGrid(self, size):

    grid = [[-1 for x in range(size)] for y in range(size)] 

    grid[0][0] = random.randint(50,70) #self.max
    grid[self.max][0] = random.randint(50,70) #self.max / 2
    grid[self.max][self.max] = random.randint(50,70) # 0
    grid[0][self.max] = random.randint(50,70) #self.max / 2


    for index, i in enumerate(grid):
        for index2, b in enumerate(i):
            result = '{0:.3g}'.format(list1[index][index2]*100)
            print str(result),
    print()
    return grid

def getGrid(self):
    return self.grid

输出

^{pr2}$

Tags: inselfforsizereturndefrangerandom

热门问题