问题描述
就像标题所说的那样,我一直在研究康威生命游戏的 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 网格)
解决方法
考虑这个具有相同结果的更简单的解决方案:
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())