列表附加内存错误

2024-10-01 04:50:06 发布

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

所以我有一段代码,我试图为房间网格生成层次布局。第一次通过主循环时,它运行得很好,并且完全执行了它应该执行的操作,但是第二次在第一次打印错误之后暂停,并给出了附加的错误,我无法找出它的错误。 (y/n提示符仅用于降低程序的速度,以便我可以看到正在发生的情况)


userInput = ""

roomChance = 0.5

world = [[0,0,0], \
         [0,1,0], \
         [0,0,0]]

possibleWorld = []

newX = []


def check_neighbours(xy):
    possibleWorld.clear()
    yLoops = 0
    for y in xy:
        print("  y:", y)
        xLoops = 0
        for x in y:
            print("  x:", x)

            #Check left cell
            if(xLoops-1 >= 0):
                if(y[xLoops-1] == 1):
                    possibleWorld.append([xLoops, yLoops])
                print("x-1:", y[xLoops-1])

            #Check right cell
            if(xLoops+1 < len(y)):
                if(y[xLoops+1] == 1):
                    possibleWorld.append([xLoops, yLoops])
                print("x+1:", y[xLoops+1])

            #Check above cell
            if(yLoops-1 >= 0):
                if(xy[yLoops-1][xLoops] == 1):
                    possibleWorld.append([xLoops, yLoops])
                print("y-1:", xy[yLoops-1][xLoops])

            #Check above cell
            if(yLoops+1 < len(xy)):
                if(xy[yLoops+1][xLoops] == 1):
                    possibleWorld.append([xLoops, yLoops])
                print("y+1:", xy[yLoops+1][xLoops])            


            print("\n")

            xLoops += 1

        yLoops += 1

def assign_neighbours(possible, world, chance):
    for i in possible:
        if(random.random() < chance):
            world[i[1]][i[0]] = 1
    possible.clear()

def border_expand(world):

    for x in world[0]:
        if(x == 1):
            for i in world[0]:
                newX.append(0)
            world.insert(0, newX)
            newX.clear
            break


def print_world(world):
    for y in world:
        print(y)


# ==================== Mainloop ====================
while(True):

    userInput = input(print("Generate Level? Y/N?"))    

    check_neighbours(world)

    print(possibleWorld)

    assign_neighbours(possibleWorld, world, roomChance)

    print_world(world)

    border_expand(world)

    print("\n")

    print_world(world)

  File "C:\Users\Potato\Desktop\Level gen_query.py", line 96, in <module>
    border_expand(world)
  File "C:\Users\Potato\Desktop\Level gen_query.py", line 67, in border_expand
    newX.append(0)
MemoryError```

Tags: inforworldifdefcheckcellprint
1条回答
网友
1楼 · 发布于 2024-10-01 04:50:06

您没有调用newX.clear,因此它在不断增长。当您运行world.insert(0, newX)时,您正在将对newX的引用插入到world[0]中,即使调用了newX.clear(),您也不会得到您想要的行为,因为world中的第一个元素将为空

您需要在每次调用border_expand时创建一个新列表,以便每次都是一个新列表

def border_expand(world):
    newX = []
    for x in world[0]:
        if(x == 1):
            for i in world[0]:
                newX.append(0)
            world.insert(0, newX)
            break

相关问题 更多 >