Just starting to learn python here. I want to make two groups, where each sprite in one group chases whichever sprite in the other group it is closest to.
I have a code where all the sprites in a group chase a single sprite from another group.
def chase(sprite, group):
for entity in group:
if math.hypot(entity.rect.centerx - sprite.rect.centerx, entity.rect.centery - sprite.rect.centery) < 1200:
if entity.rect.left - sprite.rect.left < 0:
entity.rect.left += 2
else:
entity.rect.left -= 2
if entity.rect.top - sprite.rect.top < 0:
entity.rect.top += 2
else:
entity.rect.top -= 2
I can also make all the sprites in the group getting chased run from a single sprite in the other group:
def run(sprite, group):
for entity in group:
if math.hypot(entity.rect.centerx - sprite.rect.centerx, entity.rect.centery - sprite.rect.centery) < 65:
if entity.rect.left - sprite.rect.left < 0:
entity.rect.left -= 9
else:
entity.rect.left += 9
if entity.rect.top - sprite.rect.top < 0:
entity.rect.top -= 9
else:
entity.rect.top += 9
I can't figure out how to get it so the entire group reacts, though. As in, sure, the whole group will chase, but they'll only go after 1 sprite. I can't the whole group to chase the entire other group. And I can't tell the entire other group that they should run from ALL of the chasers, not just one.
In order to do this, I want to find out which sprite from a group is closest, but I'm not sure how to do that. I tried playing around with this:
enemy = min([e for e in chased], key=lambda e: pow(e.x-entity.x, 2) + pow(e.y-entity.y, 2))
But was told the group is not iterable.
Can anyone help me with these two things? Having the whole group of chasers look through the whole other group of chasers, and then moving towards whoever is closest?
Thank you for the help!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…