'How to delete one sprite from a group(list), while it is iterating?
I want that if a bullet is touching (ghost), the one ghost from the group(list) would disappear. Here is a part of the code. Ps; I'm sorry for my previous questions
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)
Solution 1:[1]
If the Glosts overlap and you just want to delete the fist ghost touching the bullet, you need to pass False to the dokill1 argument of pygame.sprite.groupcollide() and manually kill() the first ghost:
ghosttruffet = pygame.sprite.groupcollide(
ghostgruppe, bulletgruppe, False, True, pygame.sprite.collide_mask)
if ghosttruffet:
list(ghosttruffet.keys())[0].kill()
See pygame.sprite.groupcollide():
Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rabbid76 |
