2013-04-04 74 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)转到第一行的第一个字符。