當我把對象從Game對象的內部移出時,我的代碼運行正常,但我想在它內部定義它們。該程序應該將數據對象中的字符串輸入列表中的一個列表中,列表中有一個列表,該列表中的數據爲瓦片。但我只是得到這個錯誤消息的任何想法?對象中的對象(名稱'遊戲'沒有定義)
import pygame
class Map:
grid = [[],[],[],[],[],[],[],[],[],[]]
def __init__(self):
self.loadMap("Test")
self.printMap()
def loadMap(self, mapno):
for x in range(10):
for y in range(10):
#print(str(data.map_1[x][y])+", ("+str(x)+","+str(y)+")")
#print(len(self.grid[0]))
self.grid[x].append(Tile(game.data.map_1[x][y], x, y))
def printMap(self):
pass
class Tile:
def __init__(self, tile, x, y):
self.name, self.color = game.data.tile_type[str(tile)]
self.x, self.y = x, y
self.rect = pygame.rect.Rect((self.x*50),(self.y*50),50,50)
class Data:
tile_type = {
"0":("Sea", (5, 28, 179)),
"1":("Forest", (18, 122, 15)),
"3":("River", (61, 181, 245)),
"4":("Sand", (232, 232, 30)),
"2":("Grass", (33, 235, 26)),
"5":("House", (87, 61, 31))
}
map_1 = ((0,0,0,0,0,0,0,0,0,0),
(0,0,0,4,4,4,4,0,0,0),
(0,4,4,4,2,2,5,4,0,0),
(0,4,1,2,3,2,2,4,0,0),
(0,4,1,5,3,2,1,4,0,0),
(0,4,1,2,1,3,1,4,0,0),
(0,4,4,4,4,3,1,4,0,0),
(0,0,0,0,0,4,3,4,0,0),
(0,0,0,0,0,4,1,4,0,0),
(0,0,0,0,0,0,4,0,0,0))
class Game:
def __init__(self):
self.data = Data()
self.map = Map()
pygame.init()
size = 500
self.surface = pygame.display.set_mode((size,size))
self.main()
def main(self):
while True:
self.ev = pygame.event.poll()
if self.ev.type == pygame.QUIT:
break
surface.fill((255, 240, 53))
pygame.time.delay(10)
game = Game()
錯誤消息
Traceback (most recent call last):
File "C:\Users\Amanda\Downloads\Tilesets.py", line 62, in <module>
game = Game()
File "C:\Users\Amanda\Downloads\Tilesets.py", line 50, in __init__
self.map = Map()
File "C:\Users\Amanda\Downloads\Tilesets.py", line 6, in __init__
self.loadMap("Test")
File "C:\Users\Amanda\Downloads\Tilesets.py", line 13, in loadMap
self.grid[x].append(Tile(game.data.map_1[x][y], x, y))
NameError: name 'game' is not defined
那裏只是沒有被定義爲'該方法game'什麼。它與車輪內的物體或車輪內的物體沒有任何關係。那裏只是沒有一個「遊戲」,所以Python的抱怨。您可能應該將'game'實例作爲參數傳遞給您的'Map'構造函數。 – pvg