以下是Train类的代码:
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)
如何让每个火车实例都独一无二?
答案 0 :(得分:1)
您的代码会创建一个变量列,但从不使用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)
阅读docs: pygame.sprite.Group 并piman's sprite pygame tutorial
如果我想更改其中一列的变量怎么办?
# 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,使用gas,因为SpriteGroup.update调用了Sprite.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
答案 1 :(得分: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
!伪代码!