Search code examples
pythonoopmultidimensional-arraypygametile

How can I define multiple class objects with a for loop in python?


So I am making a basic tile based game with pygame. I need to render a 20x20 grid of ground tiles on the screen. I want every tile to be an object of a class because the player will be able to change the environment.

I need to store the tile objects in a 2D array. My problem is defining all the objects using a for loop, each of the objects having a different name and properties.

Is this even possible to do or is there a better way of rendering tiles in pygame?

This is the class, there is no point is showing other tile rendering code since it doesn't even remotely work:

visGround = [[]]

class groundTile(object):
    def __init__(self, tileType, act_x, act_y, game_x, game_y):
        self.tileType = tileType
        self.act_x = act_x
        self.act_y = act_y
        self.game_x = game_x
        self.game_y = game_y

Thanks in advance!


Solution

  • This should do what you need,

    gridHeight = 20
    gridWidth = 20
    
    visGround = []
    
    
    class groundTile(object):
        def __init__(self, tileType, act_x, act_y, game_x, game_y):
            self.tileType = tileType
            self.act_x = act_x
            self.act_y = act_y
            self.game_x = game_x
            self.game_y = game_y
    
    
    for i in range(gridHeight):
        visGround.append([])
        for j in range(gridWidth):
            visGround[i].append(groundTile('Title Type', 'Act X', 'Act Y', j, i))
    
    print(visGround)
    

    You can adjust the size of the grid at the top and it will change the size of the 2 arrays. I have placed i and j in the game x and y on the assumption that these represent the location on the grid.