Search code examples
pythonfunctioninheritancecompositionfile-writing

How Write a Function Into an Open File in Python?


So I have two functions. One generates a random maze (make_maze) and the other opens and closes a file (MapFileMaker). I want to insert the maze into the text file. It's only writing the first two lines and I'm not sure how to strip a function.

Here's what the code looks like currently:

#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()

Here is what a randomly generated maze looks like:

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

And here's what's getting put into the text file:

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

The top line represents a boundary and is the same in all mazes. The second line changes depending on the maze.

I'm new to python and any help is greatly appreciated!


Solution

  • The problem isn't with your writing of the maze to the file, but in its construction. In particular, you return from make_maze after glueing together only a single pair from hor, ver here:

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

    I'm guessing you want to do something more like:

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

    but I haven't studied your walk routine too closely.