我在一個遊戲中工作,並得到一個奇怪的錯誤,其中實例變量沒有正確保存(據我所知)。當我嘗試從RunGame實例訪問self.game時,會發生這種情況。順便說一下這些類是在不同的模塊中,並且我不會顯示所有的代碼。遊戲運行良好,但切換級別時,它只是崩潰在非屬性變量上獲取屬性錯誤
class RunGame(object):
def __init__(self):
self.makeTk()
self.currentLevel = 0
self.bricksLayout = [ #for debugging: a layout of bricks. 3d array with each level
[
[0,1,0,1,1,1,1,1],
[0,0,0,0,4,1,1,1],
[4,4,4,4,4,4,4,4]
],
[
[4,0,0,1,0,1,0,1],
[0,0,0,0,0,1,0,1],
[4,4,4,4,4,4,4,4]
]
]
self.game = GameInstance(self.bricksLayout,self)
self.game.run = False #this does nothing for some reason, no error though
def switchLevel(self):
print("switching level")
self.game.run = False #calling this will give no attribute error
#self.game.clearCanvas()
#self.game.canvas.destroy()
self.currentLevel+=1
#self.game = Game(self.bricksLayout,self)
def makeTk(self):
self.root = Tk()
self.root.title("PrakeOut")
self.screen_width = self.root.winfo_screenwidth(); #monitor size
self.screen_height = self.root.winfo_screenheight();
#root.wm_attributes("-fullscreen",True) #this gives fullscreen, but removes the menu
self.root.resizable(0,0) #cant be resized
self.root.configure(background="Black") #bg color of root windw
#root.geometry("%ix%i+0+0" % (SCREEN_WIDTH, SCREEN_HEIGHT)) #maximizes screen. First two are width and height, other two are x1 and y1
#root.wm_attributes("-topmost",1); #places window in foreground
run = RunGame()
class GameInstance(object):
def __init__(self, bricksLayout,gameHandler):
self.bricksLayout = bricksLayout
self.gameHandler = gameHandler
self.run = True #game loop
self.makeCanvas()
self.brickList = [] #the list of all da created bricks
self.makeBricks()
self.makeBallAndPaddle()
self.gameLoop()
self.root.mainloop(); #needs to run main loop otherwise windows doesnt show
它給出了這樣的錯誤:
文件「C:\用戶\博倫\桌面\ Python項目\突圍\ PythonApplication1 \ PythonApplication1 \ GameHandler。 py「,第30行,在switchLevel self.game.run = False #calling這將不會給屬性錯誤 AttributeError:'RunGame'對象沒有屬性'遊戲' 按任意鍵繼續。 。 。
你的代碼張貼不能給你說的錯誤,因爲它有其他錯誤。 –
這非常有幫助。 –