首页 > 解决方案 > 为世界生成读取文件的生命游戏 - 字符串索引超出范围问题

问题描述

就像标题说的那样,我正在用 Python 开发康威生命游戏的变体,它可以从文件中读取“世界”并从中生成起始世界。但是,在我的代码中,我在 while(aLine[currentCharacter] != NEWLINE) 这一行遇到了“字符串索引超出范围”的问题,我不知道为什么。

如果有帮助,在输入文件中“”被视为死细胞,“*”被视为活细胞。

感谢您的帮助,如果我应该提供任何其他信息,请告诉我

def fileReadWorld():
    fileOK = False
    world = [] 
    row = 0
    column = 0
    while (fileOK == False):
        try:
            filename = input("Name of input file: ")        
            inputfile = open(filename,"r") 
            fileOK = True
            aLine = inputfile.readline()
            if(aLine == ""):
                print("The file %s" %(filename), "is empty.")
                fileOK = False
            else:
                aLine = inputfile.readline()
                row = 0
                while(aLine != ""):
                    currentCharacter = 0
                    world.append([])
                    while(aLine[currentCharacter] != "\n"):
                        world[row].append(aLine[currentCharacter])
                        currentCharacter = currentCharacter + 1
                    row = row + 1  
                    aLine = inputfile.readline()                                                 
                inputfile.close()
                maxRows = row
                maxColumns = len(world[0]) 
                return(world, maxRows, maxColumns)
        except IOError:
            print("Problem reading from file %s" %(filename))
            fileOK = False

我正在使用的输入文件是

    *     
     *    
   ***    
          
          
          
          
          
          

(它应该显示为 10x10 网格)

标签: pythonconways-game-of-life

解决方案


考虑这个具有相同结果的更简单的解决方案:

def main():
    world = [] 
    while True:
        try:
            filename = input("Name of input file: ")        
            for aLine in open(filename,"r") 
                world.append(list(aLine[:-1]))
            if world:
                maxRows = len(world)
                maxColumns = len(world[0]) 
                return world, maxRows, maxColumns
            print("The file %s" %(filename), "is empty.")
        except IOError:
            print("Problem reading from file %s" %filename)

print(main())

推荐阅读