Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - How to have each sprite in a group A chasing the closest sprite in group B?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[...] group is not iterable.

If chased is a pygame.sprite.Group object, then you can get a list of pygame.sprite.Sprite objects by the method sprites():

enemy = min([e for e in chased.sprites()], 
            key=lambda e: pow(e.x-entity.x, 2) + pow(e.y-entity.y, 2)) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...