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

时间:2015-02-28 05:30:16

标签: python function inheritance composition file-writing

所以我有两个功能。一个生成随机迷宫(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的新手,非常感谢任何帮助!

1 个答案:

答案 0 :(得分:4)

问题不在于您将迷宫写入文件,而在于其构造。特别是,return来自make_maze的{​​{1}}之后的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

但我没有仔细研究过你的{{1}}例程。