2013-04-04 70 views
1

我正在創建一個簡單的RPG作爲學習體驗。在我的代碼中,我有一個在25x25網格上顯示的圖塊數組,以及一個單獨的數組,其中包含True/False值與瓦塊是否固定有關。後者不起作用;在我的下面的代碼中,我已經把打印語句準確地放在了沒有到達的地方,而且我不太確定問題出在哪裏。循環沒有完全迭代

另外,關卡的數據只是一個文本文件,其格式爲25x25個字符的表示塊。

def loadLevel(self, level): 
    fyle = open("levels/" + level,'r') 
    count = 0 
    for lyne in fyle: 
     if lyne.startswith("|"): 
      dirs = lyne.split('|') 
      self.north = dirs[1] 
      self.south = dirs[2] 
      self.east = dirs[3] 
      self.west = dirs[4] 
      continue 

     for t in range(25): 
      tempTile = Tiles.Tile() 
      tempTile.value = lyne[t] 
      tempTile.x = t 
      tempTile.y = count 
      self.levelData.append(tempTile) 
     count += 1 

    rowcount = 0 
    colcount = 0 

    for rows in fyle: 
     print('Doesnt get here!') 
     for col in rows: 
      if col == 2: 
       self.collisionLayer[rowcount][colcount] = False 
      else: 
       self.collisionLayer[rowcount][colcount] = True 
      colcount += 1 
      print(self.collisionLayer[rowcount[colcount]]) 
     if rows == 2: 
      self.collisionLayer[rowcount][colcount] = False 
     else: 
      self.collisionLayer[rowcount][colcount] = True 
     rowcount += 1 

    print(self.collisionLayer) 

問題到底在哪裏?我覺得這是一個快速解決方案,但我根本沒有看到它。謝謝!

回答

5

您通過第一個for循環讀取文件一次,因此第二個循環沒有剩下可讀的內容。尋求迴文件的開頭開始第二循環前:

fyle.seek(0) 

雖然我只是緩存行作爲一個列表,如果可能的話:

with open('filename.txt', 'r') as handle: 
    lines = list(handle) 

此外,您還可以替換此:

if rows == 2: 
    self.collisionLayer[rowcount][colcount] = False 
else: 
    self.collisionLayer[rowcount][colcount] = True 

有了:

self.collisionLayer[rowcount][colcount] = rows != 2 
+0

啊!我不知道它是如何工作的。謝謝! – 2013-04-04 22:08:31

1

循環:

for lyne in fyle: 

...讀取所有的fyle和葉沒什麼由循環讀:

for rows in fyle: 
0

我想你只需要重新打開文件。如果我記得,python會從你離開的地方繼續前進。如果什麼都沒有留下,它什麼也讀不了。 您可以重新打開它,也可以使用fyle.seek(0)轉到第一行的第一個字符。