当我从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
答案 0 :(得分:2)
如果要访问Game
实例中的Map
实例,则可以在实例化时将self
传递给Map
,并将其分配给{其Map
中的{1}}实例:
__init__
然后,当您想要使用它时,您只需使用class Map:
def __init__(self, game):
self.game = game
...
class Game:
def __init__(self):
...
self.map = Map(self)
...
:
self.game
正如abccd指出的那样,你可能应该在self.grid[x].append(Tile(self.game.data.map_1[x][y], x, y))
之外调用main()
:
__init__
答案 1 :(得分:0)
问题依赖于此:
game = Game()
游戏永远不会完成初始化,因为你的程序仍然在def __init__
内,因为你在self.main()
中有一个主循环时调用了main
。从技术上讲,游戏实例还没有完全定义。你可以改变的是做这件事。通过调用main
之外的__init__
函数。
class Game:
def __init__(self):
self.data = Data()
self.map = Map()
pygame.init()
size = 500
self.surface = pygame.display.set_mode((size,size))
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()
game.main() # calling the main function here