Steve104
Steve104

Reputation: 77

Pygame update the score when enemies collide

pygame.sprite.groupcollide(Enemy_List,Bullet_List,True,True,Score_Change())

def Score_Change():
    global Score
    Score += 1
    print(Score) #For testing purposes

This line makes two enemies who collide disappear. However the function at the end always is on for some reason and i want it to only come on when the enemies collide

Upvotes: 0

Views: 390

Answers (2)

Rodolfo
Rodolfo

Reputation: 593

From the documentation:

groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict

The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a “rect” value, which is a rectangle of the sprite area, which will be used to calculate the collision.

The function that you are passing Score_Change is being called to check if two units collide.

groupcollide returns a dictionary of elements that have collided. That could help you calculate the score by checking how many enemies have collided:

collisions = pygame.sprite.groupcollide(Enemy_List,Bullet_List,True,True)
increment_score(len(collisions))

def increment_score(amount = 1):
    global Score
    Score += amount
    print(Score) #For testing purposes

PS: this function does not handle the removal of the two enemies that collide

Upvotes: 0

sloth
sloth

Reputation: 101142

Everytime this line

pygame.sprite.groupcollide(Enemy_List,Bullet_List,True,True,Score_Change())

is executed, Score_Change() will be called, the code inside this function will be executed, and its return value (None), will be passed to the groupcollide function as collided argument.

Note that the last parameter expects a function that calculates if two sprites collide. From the documentation:

The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a “rect” value, which is a rectangle of the sprite area, which will be used to calculate the collision.

You usually pass a function like pygame.sprite.collide_mask or pygame.sprite.collide_circle as this argument.

So it seems you expect Score_Change to be called if a collision happens. That's not the case. What you could do is something like:

for k, v in pygame.sprite.groupcollide(Enemy_List,Bullet_List,True,True):
    # k is the enemy
    # v is a list of bullets that them
    global Score
    Score += 1
    print(Score) 

Upvotes: 2

Related Questions