[英]How can I define multiple class objects with a for loop in python?
So I am making a basic tile based game with pygame.所以我正在用 pygame 制作一个基于瓷砖的基本游戏。 I need to render a 20x20 grid of ground tiles on the screen.我需要在屏幕上渲染一个 20x20 的地砖网格。 I want every tile to be an object of a class because the player will be able to change the environment.我希望每个图块都是 object 的 class 因为玩家将能够改变环境。
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.我的问题是使用 for 循环定义所有对象,每个对象都有不同的名称和属性。
Is this even possible to do or is there a better way of rendering tiles in pygame?这甚至可以做到,还是有更好的方法在 pygame 中渲染图块?
This is the class, there is no point is showing other tile rendering code since it doesn't even remotely work:这是 class,没有必要显示其他瓷砖渲染代码,因为它甚至无法远程工作:
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!提前致谢!
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.您可以调整顶部网格的大小,它将改变 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.我在游戏 x 和 y 中放置了 i 和 j,假设它们代表网格上的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.