删除/删除sprites.Group()中的前N个或后N个

时间:2013-04-18 13:07:19

标签: python python-2.7 pygame

所以,假设你有一个sprites组,你添加了很多东西:

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

来修改组

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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()