Creature constructor()
The constructor is where an object's initial state is set up. Here it also implements the genetic algorithm's inheritance step: pass parentGenes in and you get evolution, leave it null and you get a randomly seeded founder.
🔬 This branch decides between fresh random genes and mutated inherited genes. What happens if you force EVERY creature (even generation 0) through mutateGenes by always taking this branch - would the population still be diverse?
if (parentGenes) {
// If a parent's genes are provided, mutate them for the offspring
this.genes = this.mutateGenes(parentGenes);
} else {
constructor(x, y, parentGenes = null, generation = 0) {
this.x = x;
this.y = y;
this.size = 20; // Initial size, grows with food, shrinks with hunger
// Randomized color for visual distinction
this.color = color(random(100, 255), random(100, 255), random(100, 255));
this.speed = 2; // Base movement speed
this.angle = random(TWO_PI); // Initial movement direction
this.generation = generation; // Track which generation this creature belongs to
// Genes (traits)
if (parentGenes) {
// If a parent's genes are provided, mutate them for the offspring
this.genes = this.mutateGenes(parentGenes);
} else {
// First generation, randomize genes completely
this.genes = {
visionRadius: random(50, 200), // How far it can see food
hungerRate: random(0.02, 0.1), // Size lost per frame (hunger)
splitSize: random(35, 50), // Size at which it splits into offspring
mutationRate: random(0.01, 0.1), // Probability of a gene mutating
movementBias: random(-0.5, 0.5), // Preference for turning left/right (-0.5 to 0.5)
turnSpeed: random(0.02, 0.1) // How quickly it can turn towards food/random direction
};
}
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
if (parentGenes) {
Decides whether a creature gets fully random starting genes or mutated copies of a parent's genes
this.color = color(random(100, 255), random(100, 255), random(100, 255));- Picks a random RGB color biased toward bright/light values so creatures are visible on the dark background
this.angle = random(TWO_PI);- Gives the creature a random starting facing direction, in radians (0 to 2*PI)
if (parentGenes) {- Checks whether this constructor was called with a parent's gene object (i.e. this is offspring, not a founding creature)
this.genes = this.mutateGenes(parentGenes);- Runs the parent's genes through the mutation function so offspring are similar to but not identical to the parent
visionRadius: random(50, 200), // How far it can see food- Randomly assigns how many pixels away this creature can detect food - this is a core trait natural selection acts on