如何在 Python 中将函数写入打开的文件?

How Write a Function Into an Open File in Python?

所以我有两个功能。一个生成随机迷宫 (make_maze),另一个打开和关闭文件 (MapFileMaker)。我想将迷宫插入到文本文件中。它只写了前两行,我不确定如何剥离一个函数。

当前代码如下所示:

#random map
from random import shuffle, randrange
def make_maze(w = 10, h = 5):
        vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
        ver = [["   "] * w + ['+'] for _ in range(h)] + [[]]
        hor = [["+++"] * w + ['+'] for _ in range(h + 1)]

        def walk(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)] = "   "
                walk(xx, yy)

    walk(randrange(w), randrange(h))
    for (a, b) in zip(hor, ver):
        return ''.join(a + ['\n'] + b)

def MapFileMaker():

    random_map = make_maze()

    print("Do you want to try a random map?")
    again = input("Enter Y if 'yes', anything else if No: ")
    while again=="y" or again == "Y":
        mapfile = "CaseysRandMap.txt"
        out_file = open(mapfile, "w")
        out_file.write(random_map)
        out_file.close()

        print('\n')
        print("Do you want to try a random map?")
        again = input("Enter Y if 'yes', anything else if No: ")

    print("THIS IS DONE NOW")
MapFileMaker()

这是随机生成的迷宫的样子:

+++++++++++++++++++++++++++++++
+                       +     +
+  +++++++++++++  ++++  +  +  +
+        +        +  +     +  +
++++++++++  ++++  +  +++++++  +
+           +     +  +        +
+  ++++  ++++++++++  +  +++++++
+     +  +           +     +  +
+  +  ++++  +++++++++++++  +  +
+  +        +                 +
+++++++++++++++++++++++++++++++

下面是放入文本文件的内容:

+++++++++++++++++++++++++++++++
+                       +     +

顶线代表边界,所有迷宫都一样。第二行根据迷宫变化。

我是 python 的新手,非常感谢任何帮助!

问题不在于您将迷宫写入文件,而在于其构造。特别是,你从 make_mazereturn 仅将 hor, ver 中的一对粘合在一起后:

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

我猜你想做的更像是:

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

但我还没有仔细研究你的 walk 例程。