大家好,并提前感谢您的帮助。
我正在学习Python并在Zork风格的冒险游戏中练习。
一旦我定义了类,我的第一个实际指令就是
ourGame = Game('githyargi.txt')
其中githyargi.txt是一个包含所有游戏字符串的文件。方法Game.parseText()按文档记录。
Traceback显示问题:
Traceback (most recent call last):
File "githyargi.py", line 237, in <module>
ourGame = Game('githyargi.txt')
File "githyargi.py", line 12, in __init__
self.scenes[0] = Start()
File "githyargi.py", line 166, in __init__
for string in ourGame.strings['FIRST']:
NameError: global name 'ourGame' is not defined
如果我从执行块执行ourGame.scenes[0] = Start()
它很有效 - 没有名称错误,并且self.scenes[0].flavStr
充满了适当的风味文本。但是我想创建一个方法Game.makeScenes()
,它将创建游戏中的所有场景并将它们存储在列表ourGame.scenes
中。为什么Start()的 init 在从Game()的 init 实例化时看到ourGame.strings,当它从执行中实例化时可以看到相同的dict方框?
class Game(object):
def __init__(self, filename):
'''creates a new map, calls parseText, initialises the game status dict.'''
self.strings = self.parseText(filename)
self.sceneIndex = 0
self.scenes = []
self.scenes[0] = Start()
self.status = {
"Health": 100,
"Power": 10,
"Weapon": "Unarmed",
"Gizmo": "None",
"Turn": 0,
"Alert": 0,
"Destruct": -1
}
def parseText(self, filename):
'''Parses the text file and extracts strings into a dict of
category:[list of strings.]'''
textFile = open(filename)
#turn the file into a flat list of strings and reverse it
stringList = []; catList = [] ; textParsed = {}
for string in textFile.readlines():
stringList.append(string.strip())
stringList.reverse()
#make catList by popping strings off stringList until we hit '---'
for i in range(0, len(stringList)):
string = stringList.pop()
if string == '---':
break
else:
catList.append(string)
#Fill categories
for category in catList:
newList = []
for i in range(0, len(stringList)):
string = stringList.pop()
if string == '---':
break
else:
newList.append(string)
textParsed[category] = newList
return textParsed
class Scene(object):
def __init__(self):
'''sets up variables with null values'''
self.sceneType = 'NULL'
self.flavStr = "null"
self.optStr = "null"
self.scenePaths = []
class Start(Scene):
def __init__(self):
self.flavStr = ""
for string in ourGame.strings['FIRST']:
self.flavStr += '\n'
self.flavStr += string
self.optStr = "\nBefore you lies a dimly lit corridor. (1) to boldly go."
self.scenePaths = [1]
答案 0 :(得分:0)
这是时间问题。当你这样做
ourGame = Game('githyargi.txt')
然后首先创建Game实例,然后才将它分配给ourGame。
相反,将游戏传递给Scene的构造函数,并传递self
,使其变为类似
self.scenes.append(Start(self))
请注意,您也无法执行scenes = []
,然后在下一行设置scenes[0]
- 空列表中没有元素0。