python中的Boids;计算两个投标之间的距离 [英] Boids in python; calculating distance between two boids

查看:45
本文介绍了python中的Boids;计算两个投标之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python中的Boid对飞行中的鸟类的行为进行编程.我还没有发现太多,但是目前我被卡在定义两个波德峰之间距离的函数上.必须使用公式(a,b)= sqrt((a_x-b_x)^ 2 +(a_y-b_y)^ 2))进行计算,其中a和b是我必须计算距离的两个向量,a_x和b_x是向量的x分量,a_y和b_y是y分量.我在公式中收到有关索引的错误.我尝试了多种解决方法,但我不知道该怎么做...

I'm trying to program the behaviour of birds in flight with boids in Python. I haven't found much yet but currently i'm stuck on the function defining the distance between two boids. It has to be calculated with the formula (a,b) = sqrt( (a_x - b_x)^2 + (a_y - b_y)^2) ) where a and b are the two vectors between which i have to calcualte the distance, a_x and b_x are the x-components of the vectors and a_y and b_y are the y-components. I get an error about the indices in the formula. I've tried solving in in a number of ways but i just can't figure out how to do it...

这是我到目前为止所能获得的.我对编程很陌生,所以我只知道基础知识,而且我不确定其余的内容是否还可以.

Here is what i've got so far. I'm very new to programming so I only know the basics and i'm not sure if the rest of what i've got is ok.;

WIDTH = 1000            # WIDTH OF SCREEN IN PIXELS
HEIGHT = 500            # HEIGHT OF SCREEN IN PIXELS
BOIDS = 20              # NUMBER OF BOIDS IN SIMULATION
SPEED_LIMIT = 500       # FOR BOID VELOCITY
BOID_EYESIGHT = 50      # HOW FAR A BOID CAN LOOK
WALL = 50               # FROM SIDE IN PIXELS
WALL_FORCE = 100        # ACCELERATION PER MOVE


from math import sqrt
import random
X = 0
Y = 1
VX = 2
VY = 3

def calculate_distance(a,b):
    a = []
    b = []
    for x in range (len(a)):
        for y in range (len(b)):
            distance = sqrt((a[X] - b[X])**2 + (a[Y] - b[Y])**2)
            return distance


boids = []

for i in range(BOIDS):
    b_pos_x = random.uniform(0,WIDTH)
    b_pos_y = random.uniform(0,HEIGHT)
    b_vel_x = random.uniform(-100,100)
    b_vel_y = random.uniform(-100,100)
    b = [b_pos_x, b_pos_y, b_vel_x, b_vel_y]

    boids.append(b)

    for element_1 in range(len(boids)):
        for element_2 in range(len(boids)):
            distance = calculate_distance(element_1,element_2)

推荐答案

问题是:

  • 您没有将任何boid数据传递到函数中,只是索引 element_1 element_2 .所以 calculate_distance 不知道关于辫子的任何事情.
  • 即使您传递投标数据,也要为 a b 分配空列表,这意味着循环内部永远不会执行.
  • You are not passing in any boid data into your function, just the indices element_1 and element_2. So calculate_distance does not know anything about the boids.
  • Even if you were passing in boid data you are assigning empty lists to a and b , which means the inside of your loop is never executed.

您想要类似的东西

for element_1 in range(len(boids)):
    for element_2 in range(len(boids)):
        distance = calculate_distance(boids[element_1],boids[element_2])

然后

def calculate_distance(a,b):
    return sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)

这篇关于python中的Boids;计算两个投标之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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