1

I am creating a program similar to the classic "astrocrash" game, but there are multiple types of ammunition, each only affecting a specific type of target. The method self.overlapping_sprites() will recognise any overlapping sprites and act accordingly, but how do I get the program to detect if the overlapping sprite is of a specific type?

class Krabbypatty(games.Sprite):
LETTUCE = 1
TOMATO = 2
PATTY = 3
images = {LETTUCE : games.load_image("tamatoandpatty.bmp"),
                 TOMATO : games.load_image("lettuceandpatty.bmp"),
                 PATTY : games.load_image("lettuceandtomato.bmp") }
SPEED = 3
def __init__(self, x, y, krabbypattytype):
    super(Krabbypatty, self).__init__(
        image = Krabbypatty.images[krabbypattytype],
        x=x, y=y,
        dx = random.choice([1, -1]) * Krabbypatty.SPEED * random.random()/krabbypattytype,
        dy = random.choice([1, -1]) * Krabbypatty.SPEED * random.random()/krabbypattytype)
    self.krabbypattytype = krabbypattytype
def update(self):
    if self.top > games.screen.height:
        self.bottom = 0
    if self.bottom < 0:
        self.top = games.screen.height
    if self.left > games.screen.width:
        self.right = 0
    if self.right < 0:
        self.left = games.screen.width
    if self.overlapping_sprites:
        sprite.change_patty()
def change_patty(self):
gsach
  • 5,715
  • 7
  • 27
  • 42

3 Answers3

0

self.overlapping_sprints is a list of sprites, right?

Try iterating over self.overlapping_sprites

for sprite in self.overlapping_sprites:
   sprite.dosomething()

Or

sprites = [sprite for sprite in self.overlapping_sprites if sprite.whatever == 1]

I don't know what is in a sprite, but I assume you can assign a field to track what type it is. Or if there are sprite sub-types (again I don't know pygame or whatever you are using) you can use isinstance.

if isinstance(sprite, type)

Another SO answere regarding pygame and overlapping_sprites here: Object not behaving correctly

Community
  • 1
  • 1
codenheim
  • 20,467
  • 1
  • 59
  • 80
0

The most "Pygame" solution would be using pygame.sprite.Group to store sprites and pygame.sprite.groupcollide for detecting if sprites of certain types collide. So you can create enemy_type_a group for enemies and type_a_destroyers group for projectiles that could hurt that kind of enemy.

Anton Melnikov
  • 1,048
  • 7
  • 21
-1

Just use type()

e.g.

def update(self):
    for touch in self.overlapping_sprites:
        if type(touch) is wall:
            print("Hit a wall")
            self.horizontal_bounce()
        elif type(touch) is roof:
            print("you hit the roof")
            self.vertical_bounce()
        elif type(touch) is block:
            self.vertical_bounce()
        self.score.increase_score(10)

    if self.bottom>games.screen.height:
        self.block.end_game()
mkl
  • 90,588
  • 15
  • 125
  • 265