开发者

How can I create multiple unique instances of one object and add them to a list with python and pygame?

Here is the code for the Train class:

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)
    ..开发者_如何学运维.

And here is where I create the individual train instances, within the main loop:

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

How can I make each instance of train unique?


Your code creates a variable train, but never uses train*s*. I renamed the variable to train_list to make it clearer.

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)

Read docs: pygame.sprite.Group And piman's sprite pygame tutorial

What if I want to change a variable of one of the trains?

# 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()

How do I update all trains?

You can define Train.update, to use gas, since Sprite.update is called by 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


Actually, if you need to identify a train you could add a ID to every single one of them something like this:

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.

and then loop them over:

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

! Pseudo code !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜