AttributeError:'世界'对象没有属性'绘制'



所以我正在开发一款平台游戏来取乐。我试图运行代码,但出现了以下错误:

"世界"对象没有属性"绘制">

这是我的世界级:

class World():
def __init__(self, data):
self.tile_list = []
#load images
def draw():

dirt_img = pygame.image.load('assets/images/dirt.png')
grass_img = pygame.image.load('assets/images/grass.png')
row_count = 0
for row in data:
col_count = 0
for tile in row:
if tile == 1:
img = pygame.transform.scale(dirt_img, (tile_size, tile_size))
img_rect = img.get_rect()
img_rect.x = col_count * tile_size
img_rect.y = row_count * tile_size
tile = (img, img_rect)
self.tile_list.append(tile)
if tile == 2:
img = pygame.transform.scale(grass_img, (tile_size, tile_size))
img_rect = img.get_rect()
img_rect.x = col_count * tile_size
img_rect.y = row_count * tile_size
tile = (img, img_rect)
self.tile_list.append(tile)
col_count += 1
row_count += 1

然后我在这里调用world.draw属性:

world = World(world_data)
world.draw()

此外,如果您想知道,world_data只是一个列表,其中包含一组数字,告诉代码世界应该是什么样子。

请帮帮我,我已经试着解决这个问题很久了。

问题出在缩进上。您需要以某种方式更改它们,使draw方法成为World类的一部分。

class World:
def __init__(self, data):
self.tile_list = []
self.data = data
#load images
def draw(self):
pass

此外,当您这样做时,您需要给这个方法一个self参数,因为类中的每个方法都必须有它,除非它是静态方法。

我认为你想做某事,但你做错了。当您创建类的实例时,您放入__init__方法中的任何代码都将被执行;但是您希望稍后调用draw方法。最好的方法是,如我所说定义draw方法,然后需要将data参数保存为实例变量,无论何时需要使用,都将其用作self.data

for row in self.data:

最新更新