Skip to content

Commit

Permalink
examples: Fix boid_flockers viz (projectmesa#2492)
Browse files Browse the repository at this point in the history
Boids didn't have neighbours anymore, so the visualisation crashes. This commit fixes that.
  • Loading branch information
EwoutH authored Nov 11, 2024
1 parent e1d886e commit c53223e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
9 changes: 5 additions & 4 deletions mesa/examples/basic/boid_flockers/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,14 @@ def __init__(
self.cohere_factor = cohere
self.separate_factor = separate
self.match_factor = match
self.neighbors = []

def step(self):
"""Get the Boid's neighbors, compute the new vector, and move accordingly."""
neighbors = self.model.space.get_neighbors(self.pos, self.vision, False)
self.neighbors = self.model.space.get_neighbors(self.pos, self.vision, False)

# If no neighbors, maintain current direction
if not neighbors:
if not self.neighbors:
new_pos = self.pos + self.direction * self.speed
self.model.space.move_agent(self, new_pos)
return
Expand All @@ -71,7 +72,7 @@ def step(self):
separation_vector = np.zeros(2) # Separation vector

# Calculate the contribution of each neighbor to the three behaviors
for neighbor in neighbors:
for neighbor in self.neighbors:
heading = self.model.space.get_heading(self.pos, neighbor.pos)
distance = self.model.space.get_distance(self.pos, neighbor.pos)

Expand All @@ -86,7 +87,7 @@ def step(self):
match_vector += neighbor.direction

# Weight each behavior by its factor and normalize by number of neighbors
n = len(neighbors)
n = len(self.neighbors)
cohere = cohere * self.cohere_factor
separation_vector = separation_vector * self.separate_factor
match_vector = match_vector * self.match_factor
Expand Down
5 changes: 1 addition & 4 deletions mesa/examples/basic/boid_flockers/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@


def boid_draw(agent):
if not agent.neighbors: # Only for the first Frame
neighbors = len(agent.model.space.get_neighbors(agent.pos, agent.vision, False))
else:
neighbors = len(agent.neighbors)
neighbors = len(agent.neighbors)

if neighbors <= 1:
return {"color": "red", "size": 20}
Expand Down

0 comments on commit c53223e

Please sign in to comment.