How Do I Create Many Precise Instances Of A Class (to Access Their Attributes) Through A While/for Loop?
Solution 1:
Your example seems to have a lot going on, so I will show you how I would have organized it. I have little experience with PyGame, so I will leave the tips for your Brick class to others, but I will try to help with your storage of Bricks.
This is how I would have defined lay
:
def lay():
return [[Brick() for y in range(12)] for x in range(5)]
layoutm = lay()
This construct is called a list comprehension. It is faster than using "for" and "append" and I think it looks clearer. It will create a list containing 5 lists, which will represent the rows. Each of the rows will contain 12 Bricks.
Now to deal with editing the attributes of the bricks after they have been created:
for (row, y) in zip(layoutm, range(20, 195, 35)):
for (brick, x) in zip(row, range(20, 660, 55)):
brickSprite = brick.brick
brickSprite.rect.topleft = (y, x)
This one is a little more involved. Firstly, Python allows you to iterate over objects in any iterable object, like so:
for num in [0, 1, 2]:
print(num)
This will print out the values 0, 1 and 2. Now, zip
is a function which takes two iterable objects, and returns an iterable containing pairs of the objects. For instance:
for num_name in zip([0, 1, 2], ["zero", "one", "two"]:
print(num_name)
This will print the values (0, "zero"), (1, "one"), and (2, "two"). Now back to my snippet: first, the outer loop will iterate over each row and its y coordinate. Then, the inner loop will iterate over each brick in that row and its x coordinate. After that, we can perform operations on the bricks.
Notice I did not build the block_list and list_of_sprites in the for loops. I would do that using another list comprehension:
block_list = [brick for row in layoutm for brick in row]
list_of_sprites = [brick.brick for brick in block_list]
block_list should now contain every Brick in the layoutm list and list_of_sprites should contain the Sprites corresponding to each Brick. If you decide to make Brick subclass the Sprite class, then your can change this accordingly.
Post a Comment for "How Do I Create Many Precise Instances Of A Class (to Access Their Attributes) Through A While/for Loop?"