initial commit
[applet-bots.git] / src / appletbots / friendly / FriendlyAgent.java
blob710179edbb79c5384603727ffd606f96c7773dde
1 /*
2 * Copyright (c) 2002 Erik Rasmussen - All Rights Reserverd
3 */
4 package appletbots.friendly;
6 import appletbots.Agent;
7 import appletbots.geometry.Vector;
9 import java.awt.*;
10 import java.util.List;
12 /**
13 * A friendly agent looks at all the other agents he can see and randomly
14 * selects one to be his friend. However, he can only make another agent his
15 * friend if the other agent does not already have the agent selected as his
16 * friend. The friendly agent then tries to move toward his friend by
17 * accelerating towards him. The agent remembers who his friend is and
18 * continues to accelerate towards him as long as the friend remains visible.
19 * If the agent ever loses sight of his friend he simply selects another one at
20 * random given the selection criteria stated above. If ever a friend cannot
21 * be found the agent accelerates in a random direction to search for one.
23 * @author Erik Rasmussen
25 public class FriendlyAgent extends Agent
27 /**
28 * The selected friend
30 private Agent friend;
32 /**
33 * Constructs a new FriendlyAgent with the given parameters
35 * @param size The agent's radius
36 * @param sight The distance the agent can see
37 * @param maxSpeed The maximum speed the agent can travel
38 * @param maxAcceleration The maximum acceleration for this agent
40 public FriendlyAgent(final int size, final int sight, final double maxSpeed, final double maxAcceleration)
42 super(size, sight, maxSpeed, maxAcceleration);
43 this.color = Color.cyan;
46 /**
47 * Observes the world, and follows the Friendly Agent Algorithm.
49 public void observeWorld()
51 final List neighbors = world.getNeighbors(this);
52 if (neighbors.isEmpty())
53 friend = null;
54 else
56 if (friend == null || !neighbors.contains(friend))
58 // remove neighbors that have me as their friend
59 for (int i = 0; i < neighbors.size(); i++)
61 final Agent neighbor = (Agent) neighbors.get(i);
62 if (neighbor instanceof FriendlyAgent)
64 final FriendlyAgent friendlyNeighbor = (FriendlyAgent) neighbor;
65 if (equals(friendlyNeighbor.getFriend()))
66 neighbors.remove(i--);
69 if (neighbors.isEmpty())
70 friend = null;
71 else
73 // can't follow old one, pick a random neighbor and go to him
74 final int randIndex = (int) Math.floor(Math.random() * neighbors.size());
75 friend = (Agent) neighbors.get(randIndex);
79 if (friend != null)
80 setAcceleration(world.getVectorToObject(this, friend));
81 else
82 setAcceleration(Vector.getRandom(maxAcceleration));
85 /**
86 * Returns the selected friend
88 * @return The selected friend
90 public Agent getFriend()
92 return friend;