Search code examples
pythonobjectpygamesprite

Difficiating objects in a group


In a group called powerUpGroup, there are two objects: speedUp and jumpUP. The following code checks if the player object has collided with any objects in the group:

for eachPowerUp in powerUpGroup:        
    if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False) :
        eachPowerUp.kill()

Let's say I only want the program to print "Speed increased" when the player collides with speedUp object. Based on the code above, it will print the message if it either speedUp or jumpUP since they are in the same group. Without creating a new group, is there a way for python to identify that they are different objects run certain code?


Solution

  • Use an if statement to check if the power-up is speedUp

    for eachPowerUp in powerUpGroup:        
        if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False):
            if eachPowerUp == speedUp:
                print("Speed increased")
            eachPowerUp.kill()
    

    Edit for second part of question: Instead of checking if the power up is a certain object, you can check if it is a certain class. Say you have a class called SpeedUp. You can check to see if eachPowerUp is a SpeedUp object and then print the message you wanted.

    for eachPowerUp in powerUpGroup:        
        if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False):
            if type(eachPowerUp) == SpeedUp:
                print("Speed increased")
            eachPowerUp.kill()