因此,我试图创建一个简单的世界生成使用代码,我目前了解。为此,我创建了一个二维数组,使用0作为零,1作为绘图函数。我首先使用输入变量创建一个空白世界,然后计划使用生成脚本更新数组。但是,当尝试更新world[0][x]时,它会更新每个列表中位于“x”位置的每个项目
这是我的密码:
import random
worldHeight = 10 #int(input("What is the world height? "))
worldLength = 5 #int(input("What is the world length? "))
terrainHeight = 5 #int(input("What is the terrain height? "))
step = 2 #int(input("What is the step? "))
world = []
worldBlankRow = []
def createBlank():
global worldLength, worldHeight, world, worldBlankRow
for n in range(0,worldHeight):
worldBlankRow.append(0)
for n in range(0,worldLength):
world.append(worldBlankRow)
print(world)
def generate():
global world, worldHeight, worldLength,terrainHeight
counter=0
#randomStep = random.randint(-(step),step)
#while counter <= worldLength:
for x in range(worldHeight-terrainHeight,worldHeight):
world[0][x] = 1
print(world)
#counter=counter+1
#print(counter)
createBlank()
generate()
这是我的输出,你可以看到哪里出了问题:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0]]
[[0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0]]
[[0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 0]]
[[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]
正如您所看到的,每个列表都在更新,我要生成一个,然后是下一个,然后是下一个。你知道吗
问题是您将
worldBlankRow
附加到world
。现在这意味着确切的同一个对象被多次附加到world
。稍后,当您更改world
的一个元素时,您将更改所有元素,因为它们实际上都指向相同的worldBlankRow
。你需要一份单独的副本。尝试:相关问题 更多 >
编程相关推荐