0

So I am working on a platformer game for fun. I try to run the code but this error comes up:

'World' object has no attribute 'draw'

This is my world class:

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

and then I call the world.draw attribute here:

world = World(world_data)
world.draw()

Also, in case you were wondering, world_data is just a list that holds a bunch of numbers that tell the code what the world should look like.

Please help me, I have been trying to fix this for ages.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Is your indentation correct? – crayxt Jun 07 '21 at 04:48
  • 1
    well if the indentation here matches your code, the class isn't properly structured so it thinks the `draw` method is part of the `__init__` function which isn't part of the `World` class at all – Matthew Barlowe Jun 07 '21 at 04:49

1 Answers1

0

The problem is with you indentations. You need to change them in a way so the draw method become a part of the World class.

class World:
    def __init__(self, data):
        self.tile_list = []
        self.data = data

    #load images
    def draw(self):
        pass

Also when you did that, you need to give this method a self parameter, because every method in a class must have it unless it's a static method.

I think you are trying to do something but you are doing it wrong. Any code that you put inside the __init__ method will be executed when you create an instance of the class; But you want to call the draw method later. Best way to do so is that you define the draw method as I said and then you need to save the data argument as an instance variable and whenever you need to use it, use it as self.data

for row in self.data:
aaronn
  • 448
  • 1
  • 6
  • 16