如何通过while / for循环创建一个类的许多精确实例(以访问其属性)? [英] How do I create many precise instances of a class (to access their attributes) through a while/for loop?

查看:109
本文介绍了如何通过while / for循环创建一个类的许多精确实例(以访问其属性)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用pygame制作Atari突破风格的游戏,我希望易碎块成为具有某些属性的对象,随着游戏的进行,这些属性可以更改。
这样,我创建了一个 Block类和一个后续函数,该函数循环遍历该类几次,将实例分配给一个列表。
我遇到的问题是我没有为每个对象使用不同的名称,因此很难访问它们的各个属性。

I'm trying to make an atari breakout style game using pygame, and I want the breakable blocks to be objects with certain attributes that I can change as the game progresses. As such I created a "Block" class and a subsequent function that loops through this class several times assigning the instances to a list. The problem that I encountered is that I didn't have a distinct "name" for each object so that made it sort of tough to access their individual attributes.

这是一个示例:

class Block:
    def __init__(self):
        self.brick = pygame.sprite.Sprite()
        pygame.sprite.Sprite.__init__(self.brick)
        self.brick.image = pygame.Surface([width, height])
        self.brick.image.fill(RED)
        self.brick.rect = self.brick.image.get_rect()
    def blockType (self, hardness):
        self.hardness = hardness  

def lay ():
    layoutm = []
    for x in range (0, 5):
        layoutl = []
        for y in range (0, 12):
            layoutl.append (Block())
        layoutm.append (layoutl)
    return layoutm  

layoutm=lay()

horIndex = -1
for x in range(20, 195, 35):
    horIndex += 1
    verIndex = -1
    for y in range (20, 660, 55):
        verIndex += 1
        #set_trace ()
        brick = (layoutm[horIndex][verIndex]).brick
        brick.rect.topleft = (y,x)
        block_list.add(brick)
        list_of_sprites.add(brick)

一些人可能会指出,我可以简单地从 pygame.sprite.Sprite()父类继承,这可能是解决方案(可能有太多属性或某些东西),但由于某些原因对我不起作用。

Some of you might point out that I can just simply inherit from the pygame.sprite.Sprite() parent class and that might be a solution (too many attributes or something maybe) but for some reason that wasn't working for me.

layoutm = lay()之后的所有内容都是相应块的位置代码,也是我包括的唯一原因这说明我打算如何访问每个self.brick的位置属性。可能不是最好的方法,但是构造器之后的所有方法对于我打算添加到游戏中的功能都是必需的(这就是为什么我留在blockType()上以简化问题的原因)。

Everything after the layoutm=lay() is the positional code for the respective Blocks and the only reason I included it is to show how I was planning to access the position attributes of each respective self.brick. Probably not the best way to do this, but all the methods coming after the constructer are necessary for the features I intend to add to the game (which is why I left in the blockType () to simplify the problem).

我的问题基本上是,是否我总是必须使用 set_trace()之后的代码(要运行的命令)调试器 pudb )是否可以访问这些单个实例。

My question is basically if I always have to use the code that comes after the set_trace() (which is the command to run the debugger pudb) to access these individual instances or not.

仅供参考:我经历的原因所有这些东西是因为我计划有一些列表,例如

Just for information: The reason I go through all this stuff is because I plan to have some lists such as

level_1 = [  
[1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,1,1]] 

level_2 = [
[0,1,1,2,2,3,3,2,2,1,1,0],
[1,1,2,2,3,3,3,3,2,2,1,1],
[1,2,2,3,3,4,4,3,3,2,2,1],
[1,1,2,2,3,3,3,3,2,2,1,1],
[0,1,1,2,2,3,3,2,2,1,1,0]]

re展示关卡布局以说明是哪种类型的块(当然,代码会被修改以正常工作。

representing the level layout to say which type of block goes were (the code will be modified to work of course.

我的术语有时也可能是错误的(例如,我正在用法语上这堂课),例如混淆实例与对象(我称它们为相同对象,但它们可能并不相同) ),请随时问我是否不清楚。

ALSO my terminology may be wrong sometimes (I'm taking this class in French) such as confusing instances vs objects (I call them the same but they probably aren't) so feel free to ask me if something isn't clear.

推荐答案

您的示例似乎正在进行很多工作,因此我将向您展示如何组织它。我对PyGame的经验很少,因此我会将有关您的Brick类的提示留给其他人,但我会尽力帮助您存储Bricks。

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.

我会定义 lay

def lay():
    return [[Brick() for y in range(12)] for x in range(5)]
layoutm = lay()

此结构称为列表理解。它比使用 for和 append更快,我认为它看起来更清晰。它将创建一个包含5个列表的列表,这些列表将代表行。每行将包含12个积木。

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)

这个涉及更多一点。首先,Python允许您迭代任何可迭代对象中的对象,如下所示:

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)

这将打印出值0、1和2现在, zip 是一个函数,它接受两个可迭代的对象,并返回一个包含成对对象的可迭代对象。例如:

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)

这将打印值(0,零),(1,一个)和(2,两个)。现在回到我的代码段:首先,外循环将遍历每一行及其y坐标。然后,内循环将遍历

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.

注意,我没有在for循环中构建block_list和list_of_sprites。我会使用另一个列表理解

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现在应该包含layoutm列表中的每个Brick,而list_of_sprites应该包含Spri对应于每个Brick。如果您决定使Brick成为Sprite类的子类,则可以相应地对其进行更改。

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.

这篇关于如何通过while / for循环创建一个类的许多精确实例(以访问其属性)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆