1
\$\begingroup\$

I have a group containing my aliens and another containing the bullets I have fired. When I detect their collisions, I want to pull the alien's x-y co-ordinates during it's deletion so I can put an explosion animation in that location. How do I achieve this? My attempts so far give an error saying group items cannot be indexed.

This is my first real coding project - so still new. I'm using Pygame to make the game.

Current collision detection code:

def check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets,bombs):
"""Respond to bullet-alien collisions"""

collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)

#Collect X-Y co-ordinates here

if collisions:
    for aliens in collisions.values():
        stats.score += ai_settings.alien_points * len(aliens)
        sb.prep_score()
        stats.aliens_hit += 1
        stats.calc_accuracy()
        sb.accuracy()
    check_high_score(stats,sb)  
\$\endgroup\$
0
\$\begingroup\$

After much trial and error, I've found a solution that works. Rather than having a central function that loops through the groups to find collisions, I split it out so each object checks for and detects it's own collisions. It then calls the explosion animation function before deleting itself. The extra scoreboard updates have remained behind and are updated by a separate call during each run through the main loop instead.

class Alien(Sprite):    

    #other functions truncated

    def update(self,ai_settings,screen,stats,aliens,bullets,explosions):
        """Move aliens to the right or left"""
        self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction)
        self.rect.x = self.x    

        if pygame.sprite.spritecollide(self,bullets,True):
            stats.score += ai_settings.alien_points
            stats.aliens_hit += 1
            target_x = self.rect.centerx
            target_y = self.rect.centery
            gf.explode(ai_settings,screen,target_x,target_y,explosions)
            self.kill() 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.