HeightMap类包装了一个二维的浮点值数组。现在我把它保存为整数,因为它打印得更好,而且我没有机会实现任何其他特性。我遇到的问题是,当我调用set(self,x,y,value)时,它只是用代码将x,y的值设置为value”self.行[y] [x]=value”,它似乎改变了整个列,访问了self.行并将该数组的第x个成员设置为value。在
这是我的密码。我有90%的把握错误出在2数组的初始化中。在
def filledArray(length, value) :
result = []
for i in range(1, length) :
result.append(value)
return result
def resizeArray(array, newLength, nullValue) :
if newLength == len(array) :
return array
result = []
for i in range(0, newLength) :
if i < len(array) :
result.append(array[i])
else :
result.append(nullValue)
return result
class HeightMap:
"""A class that wraps a 2D array for generating height maps"""
def __init__(self) :
self.width = 0
self.height = 0
self.rows = []
def __init__(self, initWidth, initHeight) :
self.clear(initWidth, initHeight);
def clear(self, initWidth, initHeight) :
self.width = initWidth
self.height = initHeight
self.rows = filledArray(initHeight, filledArray(initWidth, 0))
def setHeight(self, newHeight) :
if self.height == newHeight :
return
self.rows = resizeArray(self.rows, newHeight, filledArray(self.width, 0))
def setWidth(self, newWidth) :
if self.width == newWidth :
return
for i in range(0, len(self.rows)) :
self.rows[i] = resizeArray(self.rows[i], newWidth, 0);
self.width = newWidth
def get(self, x, y) :
return self.rows[y][x]
def set(self, x, y, value) :
self.rows[y][x] = value
def add(self, x, y, value) :
self.rows[y][x] += value
def multiply(self, x, y, value) :
self.rows[y][x] *= value
您的问题是,当您调用
filledArray(initHeight, filledArray(initWidth, 0))
时,第二个参数是通过引用传递的(python对象总是这样)。在filledArray
中,您需要为每个文件制作一个value
的副本。这将需要在您的函数中添加一些附加逻辑,大致如下:或者你可以做一个稍微少一点的Python:
^{pr2}$创建副本。在
相关问题 更多 >
编程相关推荐