如何用Python和Pygame创建多个唯一对象实例并添加到列表中?

0 投票
2 回答
1438 浏览
提问于 2025-04-16 13:37

这是关于火车类的代码:

class Train(pygame.sprite.Sprite):
def __init__(self):
    pygame.sprite.Sprite.__init__(self) #call Sprite initializer
    self.image, self.rect = load_image('train.bmp', -1)
    ...

接下来这是我在主循环中创建每个火车实例的地方:

trains = pygame.sprite.Group()
while True:
    for event in pygame.event.get():
        if event ...:
            train = Train()
            train.add(trains)

我该如何让每个火车实例都变得独一无二呢?

2 个回答

0

其实,如果你想给每列火车一个标识,你可以给每一列火车加一个ID,像这样:

class Train(pygame.sprite.Sprite):
    def __init__(self, ID = None):
        # train goes here, maybe even a counter that changes "ID" to something if not user-defined.

然后你可以把它们一个个遍历出来:

for train in trains:
    if ID == "whatever you like":
        #Do something

!伪代码!

1

你的代码创建了一个叫做 train 的变量,但从来没有用到 train*s*。我把这个变量改名为 train_list,这样更清楚明了。

train_list = pygame.sprite.Group()
done = False # any code can toggle this , to request a nice quit. Ie ESC

while not done:
    for event in pygame.event.get():
        if event ...:
            train = Train()
            train_list.add(train)

可以查看 pygame.sprite.Group 的文档piman 的 pygame 精灵教程

如果我想改变某个火车的变量怎么办?

# modify a variable on one train
train_list[2].gas = 500

# kill train when out of gas
for cur in train_list:
    # this will call Sprite.kill , removing that one train from the group.
    if cur.gas <= 0:
        cur.kill()

我怎么更新所有的火车?

你可以定义 Train.update 方法来使用油量,因为 Sprite.update 是由 SpriteGroup.update 调用的。

Train(pygame.sprite.Sprite):
    def __init__(self):
        super(Train, self).__init__()
        self.gas = 100
    def update(self)
        self.gas -= 1 # or you can use a variable from the caller

撰写回答