initial commit
[applet-bots.git] / src / appletbots / swarm / SwarmAgent.java
bloba8b14d72e5ac802fcd56116d7470274a18331e55
1 /*
2 * Copyright (c) 2002 Erik Rasmussen - All Rights Reserverd
3 */
4 package appletbots.swarm;
6 import appletbots.Agent;
7 import appletbots.geometry.Vector;
9 import java.awt.*;
10 import java.util.ArrayList;
11 import java.util.Collections;
12 import java.util.List;
15 /**
16 * A swarm agent looks at its neighbors, chooses a certain number
17 * of them, and accelerates in the direction of their average velocity,
18 * with a part of its acceleration being randomized.
20 * @author Erik Rasmussen
22 public class SwarmAgent extends Agent
24 /**
25 * The number of neighbors to follow
27 private int numNeighborsToFollow;
29 /**
30 * Choose neighbors by proximity when true, randomly when false
32 private boolean chooseNeighborsByProximity;
34 /**
35 * Percentage of acceleration to be random
37 private double randomizationFactor;
39 /**
40 * Constructs a swarm agent with the given parameters
42 * @param size The agent's radius
43 * @param sight The distance the agent can see
44 * @param maxSpeed The maximum speed the agent can travel
45 * @param maxAcceleration The maximum acceleration for this agent
46 * @param numNeighborsToFollow The number of neightbors to follow
47 * @param chooseNeighborsByProximity How to choose neighbors to follow
48 * @param randomizationFactor The percentage of acceleration to be random
50 public SwarmAgent(final int size, final int sight, final double maxSpeed, final double maxAcceleration, final int numNeighborsToFollow, final boolean chooseNeighborsByProximity, final double randomizationFactor)
52 super(size, sight, maxSpeed, maxAcceleration);
53 this.numNeighborsToFollow = numNeighborsToFollow;
54 this.chooseNeighborsByProximity = chooseNeighborsByProximity;
55 this.randomizationFactor = randomizationFactor;
56 this.color = Color.cyan;
59 /**
60 * Observes the world, and follows the Swarm Agent Algorithm.
62 public void observeWorld()
64 final List neighbors = world.getNeighbors(this);
65 if (chooseNeighborsByProximity)
66 Collections.sort(neighbors, world.objectDistanceComparator(this));
67 else
68 Collections.shuffle(neighbors);
70 final List velocitiesOfNeighborsToFollow = new ArrayList();
71 for (int i = 0; i < neighbors.size() && i < numNeighborsToFollow; i++)
73 final Agent neighbor = (Agent) neighbors.get(i);
74 velocitiesOfNeighborsToFollow.add(world.getVelocity(neighbor));
77 final Vector randomization = Vector.getRandom(getMaxAcceleration() * randomizationFactor);
78 final Vector averageNeighborVelocity = Vector.average(velocitiesOfNeighborsToFollow).multiply(1 - randomizationFactor);
80 setAcceleration(averageNeighborVelocity.add(randomization));