如何从组(列表)中删除一个精灵,而它是迭代?



我想如果一个子弹是触摸(鬼),一个鬼从组(列表)将消失。下面是代码的一部分。Ps;很抱歉我之前的问题

import pygame, math, random, os
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction):
super().__init__() 
self.x = x + 15
self.y = y + 25
self.fx = 10
self.fy = 10
self.direction = direction
def draw_bullet(self, screen):
screen.blit(bullet_img, (self.x, self.y))
def move(self):
if self.direction == 1:
self.x += 15
if self.direction == -1:
self.x -= 15                  
def off_screen(self):
return not(self.x >= 0 and self.x <= width)

def update(self):
self.rect.x += 5
class Ghost(pygame.sprite.Sprite):
def __init__(self, x, y, fx,fy):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('ghost.png').convert_alpha()
self.rect = self.image.get_rect() 
self.rect.x = x
self.rect.y = y
self.fartx = fx
self.farty = fy 
lst = [0,1,2,3,4,5,6,7]
for i in range(len(lst)): 
ghost = Ghost(random.randint(0,width),random.randint(0,height),random.randint(1,8),random.randint(1,8))
ghostgruppe.add(ghost)

ghosttruffet = pygame.sprite.groupcollide(ghostgruppe, bulletgruppe, True, True, pygame.sprite.collide_mask)

如果Glosts重叠,而你只想删除碰到子弹的第一个鬼,你需要将False传递给pygame.sprite.groupcollide()dokill1参数,并手动kill()第一个鬼:

ghosttruffet = pygame.sprite.groupcollide(
ghostgruppe, bulletgruppe, False, True, pygame.sprite.collide_mask)
if ghosttruffet:
list(ghosttruffet.keys())[0].kill()

参见pygame.sprite.groupcollide():

group1中的每个Sprite都被添加到返回字典中。每个项目的值是group2中相交的Sprites列表。

最新更新