gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:05 25 4
gpt4 key购买 nike

所以我有两个功能。一个生成随机迷宫 (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例程。

关于python - 如何在 Python 中将函数写入打开的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28778477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com