0

我正在使用 pygame 在 python 中进行 boids 模拟。基本行为有效,但我现在正在尝试添加避障和捕食者。到目前为止,我无法弄清楚如何实现这些行为。

首先,我试图让猎物逃跑,让掠食者发起攻击。为了做到这一点,我需要以某种方式找到最近的 boid。我该怎么做?

另外,为了避障,有人可以解释一下我如何让猎物避开静态障碍物,但不主动逃离?

我的完整代码在这里(github)。对于我将如何完成这两件事,我真的很感激任何和所有的解释。

谢谢!

编辑:

fucas 向我展示了如何做到这一点,但现在我遇到了一个新问题。

对于捕食者和猎物的行为,我现在有这个:

    def attack(self, prey_list):
        nearest_prey = None
        shortest_distance = None

            for prey in prey_list:
                distX = self.rect.x - prey.rect.x
                distY = self.rect.y - prey.rect.y
                d = distX*distX+distY*distY
                if not shortest_distance or d < shortest_distance:
                    shortest_distance = d
                    nearest_prey = prey

                # do something with nearest_prey, shortest_distance
                trajectory_x = self.rect.x - nearest_prey.rect.x
                trajectory_y = self.rect.y - nearest_prey.rect.y

                self.velocityX -= trajectory_x
                self.velocityY -= trajectory_y

这对于猎物:

    def defend(self, predator_list):
        nearest_predator = None
        shortest_distance = None

            for predator in predator_list:
                distX = self.rect.x - predator.rect.x
                distY = self.rect.y - predator.rect.y
                d = distX*distX+distY*distY
                if not shortest_distance or d < shortest_distance:
                    shortest_distance = d
                    nearest_predator = predator

                # do something with nearest_prey, shortest_distance
                trajectory_x = self.rect.x - nearest_predator.rect.x
                trajectory_y = self.rect.y - nearest_predator.rect.y

                self.velocityX += trajectory_x
                self.velocityY += trajectory_y

(此代码在所有其他规则之后最后应用)。

4

1 回答 1

1

要找到最短的距离,你可以做

def attack(self, prey_list):
    d_list = []

    for prey in prey_list:
        distX = self.rect.x - prey.rect.x
        distY = self.rect.y - prey.rect.y
        d = distX*distX+distY*distY
        d_list.append(d)

    shortest_distance = min(d_list)

为了获得最短的距离和猎物,你可以做

def attack(self, prey_list):
    nearest_prey = None
    shortest_distance = None

    for prey in prey_list:
        distX = self.rect.x - prey.rect.x
        distY = self.rect.y - prey.rect.y
        d = distX*distX+distY*distY
        if not shortest_distance or d < shortest_distance
            shortest_distance = d
            nearest_prey = prey

   # do something with nearest_prey, shortest_distance
   print nearest_prey, shortest_distance
于 2016-02-03T05:46:12.153 回答