1

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!

1
  • 1
    Please clarify what you mean by each of the objects having a different name and properties. You can do a nested for loop iterating along the x and y axes, but I need more details to properly help you. Commented Apr 18, 2020 at 10:19

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.