2 * Copyright (c) 2002 Erik Rasmussen - All Rights Reserverd
4 package appletbots
.friendly
;
6 import appletbots
.Agent
;
7 import appletbots
.geometry
.Vector
;
10 import java
.util
.List
;
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
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
;
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())
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())
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
);
80 setAcceleration(world
.getVectorToObject(this, friend
));
82 setAcceleration(Vector
.getRandom(maxAcceleration
));
86 * Returns the selected friend
88 * @return The selected friend
90 public Agent
getFriend()