从if语句中删除IndexError-迷宫解决软件



所以我想编写一个迷宫解决程序,但导入迷宫时已经失败了。这是我的代码:

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:Python34python.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-file:

6 9
#########
#  #    #
#  # #  #
#  K #  #
#    #  #
#########

对不起我的英语。

您在kassiopeia0.txt的标题行中指定了一个6乘9的迷宫,但文件的其余部分包含一个9乘6的迷宫。

交换6和9,迷宫应该读得很好。对我来说的确如此。

@卢克是对的。我建议你使用以下代码:

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

最新更新