-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAntColony.java
60 lines (49 loc) · 1.22 KB
/
AntColony.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import info.gridworld.actor.Actor;
import info.gridworld.grid.Location;
import info.gridworld.grid.Grid;
import java.util.ArrayList;
import java.util.Collections;
public class AntColony extends Actor
{
private ArrayList<Ant> workers = new ArrayList<Ant>();
private int age;
private boolean fed = false;
public AntColony()
{
this(100);
}
public AntColony(int numAnts)
{
for(int i=0; i<numAnts; i++)
{
workers.add(new Ant(this));
}
setColor(null);
age = 0;
}
public void act()
{
if(fed) return;
// the best Ant is the one closest to food. see Ant.compareTo
Ant best = Collections.max(workers);
Location closest = best.followPathFrom(getLocation());
System.out.println(best+" at "+closest);
if(best.distanceFromFood() == 0){
System.out.println("FOOD LOCATED! Solution took "+age+" generations.");
fed = true;
}
Grid gr = getGrid();
gr.put(closest, best);
// since we haven't found food yet, create a new generation of
// Ants based on the previous generation's best
int numAnts = workers.size();
workers.clear();
for(int i=0; i<numAnts; i++)
{
Ant a = new Ant(this);
a.setPath(best.getPathWithMutations());
workers.add(a);
}
age++;
}
}