Skip to content

Instantly share code, notes, and snippets.

@jywarren
Last active October 13, 2015 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jywarren/e9d03f93c07f245ce933 to your computer and use it in GitHub Desktop.
Save jywarren/e9d03f93c07f245ce933 to your computer and use it in GitHub Desktop.
Queen creates workers who look for food & return to the queen.
// set basic attributes here;
// "this" means this ant you're editing now
ant.speed = 1;
ant.trailColor = 'red';
ant.height = 40;
ant.width = 40;
ant.energy = 5000;
// runs every frame:
onRun = function () {
ant.direction += Math.random()*10-5; // vary direction slightly, randomly, in degrees
ant.trail(ant.trailColor, 100); // leave a trail of <color>, <amount>
ant.color = "rgba(" + ant.energy + ", 0, 50, 1)"; // color red according to how full
// if queen has enough energy, and there are <100 ants on the field
if (ant.energy > 1000 && field.objects.length < 100) {
// make a new ant:
var child = field.populate(AntFarm.Ant, 1)[0];
// give child 1000 energy:
child.energy = 1000;
ant.energy -= 1000;
child.x = ant.x;
child.y = ant.y;
child.speed = 3;
child.queen = ant;
child.onRun = function() {
// uncomment this line for debugging energy; each ant will have a label
// child.el.html(' '+parseInt(child.energy)); // display energy
// if on top of some food and mood is not purple:
if (child.color != 'purple' && child.green() > 0) { // eat
child.color = 'yellow';
child.energy += child.green();
child.green(0); // remove the green from that patch
child.foodPlace = [child.x, child.y]; // remember that spot
if (child.energy > 1000) child.color = 'purple'; // return to queen if full
} else if (child.color == 'purple') { // return to queen
if (child.distance(child.queen) < 20) { // if already near queen
child.color = 'yellow';
child.speed = 0;
child.queen.energy += child.energy/2;
child.energy /= 2;
} else { // point at queen, fast!
child.speed = 4;
child.point(child.queen);
}
} else if (child.foodPlace) { // return to foodPlace
child.color = 'orange';
child.speed = 4;
// point at food place, but
// don't keep pointing when close to food or you get stuck:
if (child.distance(child.foodPlace) > 5) child.point(child.foodPlace);
else child.direction += Math.random()*90-45; // or just wander
} else { // forage
child.color = "rgba(" + child.energy + ", 0, 50, 1)"; // color red according to how full
child.speed = 2;
child.direction += Math.random()*10-5; // random walk
}
// if child runs out of energy
if (child.energy <= 0) {
child.color = 'grey';
child.die();
}
// leave a trail
child.trail(ant.trailColor, 255); // color, amount 0-255
}
child.remember(); // make child ant remember their instructions!
}
}
onBump = function () {
// change direction by 90 degrees:
ant.direction += 90;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment