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