如何让 A 组中的每个精灵追逐 B 组中最近的精灵? [英] How to have each sprite in a group A chasing the closest sprite in group B?

查看:49
本文介绍了如何让 A 组中的每个精灵追逐 B 组中最近的精灵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始在这里学习python.我想分成两组,其中一组中的每个精灵追逐另一组中它最接近的精灵.

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

我还可以让该组中的所有 sprite 从另一个组中的单个 sprite 运行:

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

不过,我不知道如何获得它,所以整个团队都会做出反应.当然,整个团队都会追赶,但他们只会追赶 1 个精灵.我不能整组去追整个另一组.而且我不能告诉整个其他小组他们应该远离所有追逐者,而不仅仅是一个.

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?

感谢您的帮助!

推荐答案

[...] 组不可迭代.

[...] group is not iterable.

如果 chasedpygame.sprite.Group 对象,则可以得到pygame.sprite.Sprite 对象通过方法 sprites():

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)) 

这篇关于如何让 A 组中的每个精灵追逐 B 组中最近的精灵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆