In this lesson, you’ll add collision detection to your game. To add the collision detection, you’ll use a method called .spritecollideany(), which is read as “sprite collide any.” This method accepts a Sprite and a Group as parameters. It looks at every object in the Group and checks if its .rect intersects with the .rect of the Sprite. If so, then it returns True. Otherwise, it returns False:
130# Draw all sprites
131for entity in all_sprites:
132 screen.blit(entity.surf, entity.rect)
133
134# Check if any enemies have collided with the player
135if pygame.sprite.spritecollideany(player, enemies):
136 # If so, then remove the player and stop the loop
137 player.kill()
138 running = False
For more information about collision detection, check out the following resources from the pygame documentation:
