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)
The problems are:
element_1
andelement_2
. Socalculate_distance
does not know anything about the boids.a
andb
, which means the inside of your loop is never executed.You want something like:
and then