This repository contains a simple ant simulation sketch written in Processing. It serves as an educational example for teaching generative design, object-oriented programming (OOP), animation basics, and event-driven programming.
- Install Processing from Processing.org
- Clone this repository or download the
.pde
file. - Open the
.pde
file in the Processing editor and click the "Run" button.
The Ant
class demonstrates OOP by encapsulating the properties and behaviors of an ant.
class Ant {
float x, y;
float size;
color c;
//...
}
The Ant
class constructor allows for flexibility in setting the initial x
and y
positions for each ant object.
In the draw
loop, we use dot syntax to call methods like move
and display
on each Ant
object. This is a fundamental aspect of OOP, allowing us to directly interact with individual objects. Here's how it's done:
for (Ant ants : antHill) {
ants.move();
ants.display();
}
This is saying, "For each ant in antHill
, move the ant and then display it on the screen."
The move()
method uses random()
and if
statements to give ants a random direction of movement.
void move() {
float choice = random(1);
if (choice > 0.5) {
x += random(-3, 3);
} else {
y += random(-3, 3);
}
//...
}
The display()
method uses the Processing fill
and circle
functions to display each ant object on the screen.
for (int i = 0; i<10; i+=1)
: Demonstrates a standard for-loop to initialize multiple ant objects.for (Ant ants : antHill)
: Demonstrates a for-each loop to iterate over each ant object for moving and displaying.antHill.length
: A more efficient way of getting the size of an array.i++
: A simpler way to increment each step.for(int i = 0; i < antHill.length; i++)
The code utilizes an array (antHill
) to manage multiple ant instances efficiently.
The random()
function is extensively used for varying ant movements, sizes, and colors.
mousePressed()
: Changes ant colors and sizes based on user mouse clicks.keyPressed()
: Saves the current frame when the 'S' key is pressed.
void mousePressed() {
// ...
float r = random(128, 255);
// ...
}
void keyPressed() {
if (key == 's' || key == 'S') {
saveFrame();
exit();
}
}