Search code examples
pythonlistrecursion2dmaze

is there away for me to alter this code so that it produces an output that can be stored as a 2d list?


I can print a random maze with this piece of code:

I​ want to store this to a 2d list so that I can edit it.

I have tried editing itself but this code is designed to just be printed, and nothing else.

def random_maze(w = 16, h = 8):
    vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
    ver = [["|  "] * w + ['|'] for v in range(h)] + [[]]
    hor = [["+--"] * w + ['+'] for v in range(h + 1)]

    def go(x, y):
        vis[y][x] = 1

        d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
        shuffle(d)
        for (xx, yy) in d:
            if vis[yy][xx]: continue
            if xx == x: hor[max(y, yy)][x] = "+  "
            if yy == y: ver[y][max(x, xx)] = "   "
            go(xx, yy)

    go(randrange(w), randrange(h))

    s = ""
    for (a, b) in zip(hor, ver):
        s += ''.join(a + ['\n'] + b + ['\n'])
    return s

I want the code output to be like [['+--', '+--'....etc so that I can edit it.


Solution

  • All you have do to is a small change in the part where you join a and b into s. You need to have an additional variable matrix to store the 2D list:

    s = ""
    matrix = []
    for (a, b) in zip(hor, ver):
        s += ''.join(a + ['\n'] + b + ['\n'])
        matrix.append(a)
        matrix.append(b)
    return s, matrix
    

    and finally you can retrieve the results like that:

    stringMatrix, matrix = random_maze()