Search code examples
pythonpygamecollision

How to access each items attributes in a list returned by groupcollide() in Python?


# Variable containing a list of collided objects.
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

# I want to access on of the collided objects (aliens) attribute (aliens.points)

if collisions:
    for aliens in collisions.values():
        print(aliens)
        # print(collisions.values()) returns: dict_values([[<Alien Sprite(in 0 groups)>]])
        print(aliens.points) # doesnt work
        

Terminal Output Currently:

[<Alien Sprite(in 0 groups)>]

Terminal Error Output:

AttributeError: 'list' object has no attribute 'points'


Solution

  • groupcollide works like this:

    Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.

    So you can do

    for bullet in collisions: # each bullet
        for alien in collision[bullet]: # each alien that collides with that bullet
            print(alien.points)