1

因此,假设您有一个精灵组,并且您向其中添加了一堆东西:

all_shelfs = pygame.sprite.Group()
shelf_tracking_list = []

#making shelfs
build_lvl = HEIGHT - 150
#group A
for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    all_shelfs.add(Shelf(pos[0],pos[1], pos[2]))
    build_lvl = build_lvl - 60

#group B
for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    all_shelfs.add(Shelf(pos[0],pos[1], pos[2]))
    build_lvl = build_lvl - 60
#group C
for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    all_shelfs.add(Shelf(pos[0],pos[1], pos[2]))
    build_lvl = build_lvl - 60

shelf_tracking_list = all_shelfs.sprites()

例如,如何删除 A 组?这是我添加的第一组。我注意到我不能真正使用这个shelf_tracking_list修改组

4

2 回答 2

1

如果您要跟踪每个组中的精灵,则可以使用该sprite.Group.remove(*sprites)功能删除整个组,如此处的文档中所述:http: //www.pygame.org/docs/ref/sprite.html#pygame。 sprite.Group.remove

# group A
group_a = list()
for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    new_shelf = Shelf(pos[0], pos[1], pos[2])
    group_a.append(new_shelf)
    build_lvl = build_lvl - 60
all_shelfs.add(group_a)

然后,当您想从中删除整个组时all_shelfs

all_shelfs.remove(group_a)
于 2013-04-18T13:49:16.497 回答
1

由于您要问的是如何删除逻辑组,而不仅仅是 N 个元素:根据您的程序,将精灵放在多个组中可能会大大简化事情。

您可以将一个精灵放在多个组中以引用同一个精灵。然后,如果您使用kill()它,则会将其从所有组中删除。否则remove(*groups)用于特定组的删除。

for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    shelf = Shelf(pos[0],pos[1], pos[2])
    all_shelfs.add(shelf)
    shelfs_a.add(shelf)
    build_lvl = build_lvl - 60

#group B
for i in xrange(100):
    wid = random.randint(120,320)
    pos = [random.randint(0, WIDTH-wid), random.randint(build_lvl-20, build_lvl), wid]
    shelf = Shelf(pos[0],pos[1], pos[2])
    all_shelfs.add(shelf)
    shelfs_b.add(shelf)
    build_lvl = build_lvl - 60

# ...

# then to erase from both groups
for shelf in shelfs_a:
    shelf.kill()
于 2013-04-18T17:15:01.640 回答