2015-11-22 62 views
0

所以我正在尋找代碼迷宮解決程序,我已經失敗了導入迷宮。這是我的代碼:從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是「顯示」迷宮的邊界。所以我可以計算數組中的空白元素。他們的數量將被保存在櫃檯上,至於我需要爲我補充基礎。 以及錯誤消息我revieve是:

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

Sry基因,我的英語。

回答

1

您在kassiopeia0.txt的標題行中指定了一個6乘9迷宮,但該文件的其餘部分包含一個9乘6的迷宮。

交換6和9,迷宮應該讀得很好。它爲我做了。

1

@Luke是對的。我建議你下面的代碼:

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

嘿,非常感謝你,也感謝@Luke! = d –