所以我正在寻找编码迷宫解决方案的代码,我已经失败了导入迷宫。这是我的代码:
def import_maze(filename):
temp = open(filename, 'r')
x, y = temp.readline().split(" ")
maze = [[0 for x in range(int(y))] for x in range(int(x))]
local_counter, counter, startx, starty = 0, 0, 0, 0
temp.readline()
with open(filename) as file:
maze = [[letter for letter in list(line)] for line in file]
for i in range(1, int(y)):
for z in range(0, int(x)):
if maze[i][z] == '#':
local_counter += 1
if local_counter < 2 and maze[i][z] == " ":
counter += 1
if maze[i][z] == 'K':
startx, starty = i, z
local_counter = 0
return maze, startx, starty, counter
maze, startx, starty, counter = import_maze("kassiopeia0.txt")
print(counter, "\n", startx, ":", starty, "\n", maze)
解释一下:local_counter正在“显示”迷宫的边界。所以我可以计算数组中的空白元素。它们的数量将保存在柜台中,我需要我的记忆基础。 我解除的错误信息是:
C:\Python34\python.exe C:/Users/Anton/PycharmProjects/BWINF_Aufgabe_1/Wegfinden.py
Traceback (most recent call last):
File "C:/Users/Anton/PycharmProjects/BWINF_Aufgabe_1/Wegfinden.py", line 27, in <module>
maze, startx, starty, counter = import_maze("kassiopeia0.txt")
File "C:/Users/Anton/PycharmProjects/BWINF_Aufgabe_1/Wegfinden.py", line 16, in import_maze
if maze[i][z] == '#':
IndexError: list index out of range
Process finished with exit code 1
最后这里是kassiopeia0.txt文件:
6 9
#########
# # #
# # # #
# K # #
# # #
#########
谢谢我的英语。
答案 0 :(得分:1)
你在kassiopeia0.txt的标题行中指定一个6乘9的迷宫,但文件的其余部分包含一个9乘6的迷宫。
交换6和9,迷宫应该读得很好。它确实适合我。
答案 1 :(得分:1)
def import_maze(filename):
with open(filename) as f:
maze = [[letter for letter in line.strip()] for line in f.readlines() if line.strip()]
local_counter, counter, startx, starty = 0, 0, 0, 0
for y, row in enumerate(maze):
for x, cell in enumerate(row):
if cell == '#':
local_counter += 1
elif local_counter < 2 and cell == ' ':
counter += 1
elif cell == 'K':
startx, starty = x, y
local_counter = 0
return maze, startx, starty, counter
,您的文件是:
#########
# # #
# # # #
# K # #
# # #
#########