大家好,谢谢你们的帮助。你知道吗
我正在学习Python和一个Zork风格的冒险游戏来练习。你知道吗
一旦我定义了类,我的第一个实际指令就是
ourGame = Game('githyargi.txt')
在哪里githyargi.txt文件是一个包含所有游戏字符串的文件。方法游戏.parseText()如文件所示。你知道吗
回溯显示问题:
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看不到我们的游戏.strings当从Game()的init实例化时,当从执行块实例化时,它何时可以看到相同的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]
这是个时机问题。当你这么做的时候
然后首先创建游戏实例,然后才将其分配给我们的游戏。你知道吗
相反,将要使用的游戏传递给Scene的构造器,并传递
self
,使其类似于请注意,也不能执行
scenes = []
,然后在下一行设置scenes[0]
空列表没有元素0。你知道吗相关问题 更多 >
编程相关推荐