/**
* Strength in numbers
*
*
Elie Zananiri
* CART 253, Winter 2008
*/
// ----------------------------------------------------------------------
// GLOBAL CONSTANTS
// ----------------------------------------------------------------------
int MAX_SOLDIERS = 200;
// ----------------------------------------------------------------------
// GLOBAL VARIABLES
// ----------------------------------------------------------------------
int numSoldiers = 0;
Soldier army[] = new Soldier[MAX_SOLDIERS];
PFont font;
// ----------------------------------------------------------------------
// BUILT-IN FUNCTIONS
// ----------------------------------------------------------------------
void setup() {
size(400, 400);
smooth();
noStroke();
// set up the font
font = loadFont("Georgia.vlw");
textFont(font, 12);
textAlign(CENTER, CENTER);
}
void draw() {
background(0);
step();
// draw all the soldiers
for (int i=0; i < numSoldiers; i++) {
army[i].draw();
}
}
void mousePressed() {
addSoldier(mouseX, mouseY);
}
void mouseDragged() {
addSoldier(mouseX, mouseY);
}
void keyPressed() {
if (key == ' ') {
// clear all
numSoldiers = 0;
}
}
// ----------------------------------------------------------------------
// USER FUNCTIONS
// ----------------------------------------------------------------------
/* adds a new soldier to the display */
void addSoldier(int newX, int newY) {
if (numSoldiers < MAX_SOLDIERS) {
army[numSoldiers] = new Soldier(newX, newY);
numSoldiers++;
}
}
/* moves all the soldiers and if any collide, make them fight */
void step() {
// move all the soldiers
for (int i=0; i < numSoldiers; i++) {
army[i].move();
}
// see if any two soldiers collide
for (int i=0; i < numSoldiers-1; i++) {
Soldier currSoldier = army[i];
// if the current soldier is alive...
if (currSoldier.isAlive) {
// ...go through all the current soldier's right neighbours
for (int j=i+1; j < numSoldiers; j++) {
Soldier otherSoldier = army[j];
// if the neighbour is alive...
if (otherSoldier.isAlive) {
// ...and they collide...
if (currSoldier.collidesWith(otherSoldier)) {
// ...call a fight
fight(currSoldier, otherSoldier);
}
}
}
}
}
// array to hold all soldiers that will live to the next frame
Soldier survivors[] = new Soldier[MAX_SOLDIERS];
int numSurvivors = 0;
// keep only the live soldiers for the next round
for (int i=0; i < numSoldiers; i++) {
if (army[i].isAlive) {
survivors[numSurvivors] = army[i];
numSurvivors++;
}
}
army = survivors;
numSoldiers = numSurvivors;
}
/* makes two soldiers fight, with the loser dying and the winner gaining his strength */
void fight(Soldier soldier1, Soldier soldier2) {
Soldier winner;
Soldier loser;
// randomly generate the outcome of the fight
if (random(1) < 0.5) {
winner = soldier1;
loser = soldier2;
} else {
winner = soldier2;
loser = soldier1;
}
// make the winner gain the loser's strength
winner.strength += loser.strength;
// kill the loser
loser.isAlive = false;
}