cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <div class="stats">
	<p>Current generation: <b id="generation"></b></p>
</div>
<div class="tools visible">
	<div class="field">
		<input id="show_food_perception_checkbox" type="checkbox" checked/>
		<label for="show_food_perception_checkbox">Show food perception</label>
	</div>
	<div class="field">
		<input id="show_food_attraction_checkbox" type="checkbox" checked/>
		<label for="show_food_attraction_checkbox">Show food attraction</label>
	</div>
	<div class="field">
		<input id="show_poison_perception_checkbox" type="checkbox" checked/>
		<label for="show_poison_perception_checkbox">Show poison perception</label>
	</div>
	<div class="field">
		<input id="show_poison_repulsion_checkbox" type="checkbox" checked/>
		<label for="show_poison_repulsion_checkbox">Show poison repulsion</label>
	</div>
	<div class="field">
		<input id="toggle_all_checkbox" type="checkbox" checked/>
		<label for="toggle_all_checkbox">Toggle all</label>
	</div>
	<hr />
	<div class="field range">
		<label for="">Mutation rate</label>
		<input type="range" min="0" max="1" value="0.01" step="0.01" />
		<input type="number" value="0.01" step="0.01" />
</div>
<button class="toggle_tools_btn visible" state="visible">
	<span class="open"><</span>
	<span class="close">></span>
</button>
            
          
!
            
              * {
	margin: 0;
	padding: 0;
	font: 12px monospace;
}

body {
	background: rgb(51, 51, 51);
}

canvas {
	display: block;
}

.stats {
	position: fixed;
	top: 0; left: 0;
	width: 50%;
	height: auto;
	display: table;
	padding: 10px;
	background: transparent;
	color: white;
}

.tools {
	position: fixed;
	top: 0; right: -15vw;
	width: 15vw;
	height: 100vh;
	background: rgba(0,0,0,0.5);
	opacity: 0;
	visibility: hidden;
	padding: 10px;
	transition: 0.2s ease-in-out;
}
.tools.visible {
	opacity: 1;
	right: 0;
	visibility: visible;
	transition: 0.2s ease-in-out;
}

.toggle_tools_btn {
	position: absolute;
	top: 0;
	right: 0;
	width: 30px;
	height: 30px;
	display: block;
	cursor: pointer;
	background: rgba(0,0,0,0.5);
	border: none;
	color: white;
	outline: 0;
}

.toggle_tools_btn span {
	display: flex;
	text-align: center;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 30px;
}
.toggle_tools_btn span.open {display: flex;}
.toggle_tools_btn span.close {display: none;}
.toggle_tools_btn.visible span.open {display: none;}
.toggle_tools_btn.visible span.close {display: flex;}

.toggle_tools_btn span:hover {
	background: rgba(0, 0, 255, 0.5);
}
.toggle_tools_btn.visible span:hover {
	background: rgba(255, 0, 0, 0.5);
}


.tools .field {
	display: table;
	width: 100%;
	height: auto;
	color: white;
}
.tools .field label {
	font-size: 11px;
	width: 100%;
	vertical-align: 4px;
	cursor: pointer;
}
.tools .field input[type="checkbox"] {
	width: 15px;
	height: 15px;
	margin-right: 10px;
}

.tools hr {
	margin: 10px 0;
	border: 0;
	width: 100%;
	height: 1px;
	background: rgba(255,255,255,0.25);
}
.tools .field.range {}
.tools .field.range label {
	display: block;
	margin-bottom: 4px;
}
.tools .field.range input[type="range"] {
	width: calc(70% - 10px);
	float: left;
	margin: 0;
	padding: 0;
}
.tools .field.range input[type="number"] {
	width: 30%;
	float: right;
	margin: 0;
	padding: 5px;
	border: 0;
	box-sizing: border-box;
}
            
          
!
            
              let agents = [], food = [], poison = [];

let config = {
	mutation_rate: 0.01,
	show_food_attraction: true,
	show_food_perception: true,
	show_poison_repulsion: true,
	show_poison_perception: true,
	deadzone: 50
};

let stats = {
	generation: 1
};

let elements = {};

function SteeringAgent(x, y, index, dna) {
	this.acceleration = createVector(0, 0);
	this.velocity = createVector(0, -2);
	this.position = createVector(x, y);
	this.r = 4;
	this.maxSpeed = 5;
	this.maxForce = 0.5;
	
	this.index = index;
	this.target = createVector(x, y);
	
	
	this.health = 1;
	this.dna = []
	
	if(dna === undefined) {
		this.dna[0] = random(-2, 2);// Food attraction.
		this.dna[1] = random(-2, 2);// Poison repulsion.
		this.dna[2] = random(10, 100);// Food perception.
		this.dna[3] = random(10, 100);// Poison perception.
	} else {
		for(let i=0;i<dna.length;i++) {
			this.dna[i] = dna[i];
			if(random(1) < config.mutation_rate) {
				let scale = 0.1;
				if(i <= 1) {
					this.dna[i] += random(-scale, scale);
				} else {
					scale = 10;
					this.dna[i] += random(scale, scale * 10);
				}
			}
		}
	}
	this.update = function() {
		this.health -= 0.005;
		this.velocity.add(this.acceleration);
		this.velocity.limit(this.maxSpeed);
		this.position.add(this.velocity);
		this.acceleration.mult(0);
	}
	
	this.applyDeadzone = function() {
		let dz = config.deadzone;
		let { x, y } = this.position;
		if(x <= dz) this.health -= 0.9;
		if(x > width-dz) this.health -= 0.9;
		if(y <= dz) this.health -= 0.9;
		if(y > height-dz) this.health -= 0.9;
	}
	
	this.applyForce = function(force) {
		this.acceleration.add(force);
	}
	
	
	this.behaviors = function(good, bad) {
		let steerG = this.eat(good, 0.2, this.dna[2]);
		let steerB = this.eat(bad, -0.5, this.dna[3]);
		
		steerG.mult(this.dna[0]);
		steerB.mult(this.dna[1]);
		
		this.applyForce(steerG);
		this.applyForce(steerB);
	}
	
	this.eat = function(list, nutrition, perception) {
		let record = Infinity;
		let closest = null;
		
		for(let i=list.length-1;i>=0;i--) {
			let distance = this.position.dist(list[i]);
			
			if(distance < this.maxSpeed) {
				list.splice(i, 1);
				this.health += nutrition;
			} else {
				if(distance < record && distance < perception) {
					record = distance;
					closest = list[i];
				}
			}
		}
				
		if(closest != null) {
			return this.seek(closest);
		}
		
		return createVector(0, 0);
	}
	
	this.clone = function() {
		if(random(1) < 0.001) {
			return new SteeringAgent(this.position.x, this.position.y, this.index, this.dna);
		} else {
			return null;
		}
	}
	
	this.seek = function(target) {
		// let desired = p5.Vector.sub(target, this.position);
		let desired = createVector(target.x - this.position.x, target.y - this.position.y);
		desired.setMag(this.maxSpeed);
		let steer = p5.Vector.sub(desired, this.velocity);
		steer.limit(this.maxForce);
		return steer;
	}
	
	this.dead = function() {
		return (this.health < 0);
	}
	
	this.boundaries = function() {
		let desired = null;
		let d = config.deadzone;

		if (this.position.x < d)
			desired = createVector(this.maxSpeed, this.velocity.y);
		else if (this.position.x > width -d)
			desired = createVector(-this.maxSpeed, this.velocity.y);
		if (this.position.y < d)
			desired = createVector(this.velocity.x, this.maxSpeed);
		else if (this.position.y > height-d)
			desired = createVector(this.velocity.x, -this.maxSpeed);

		if (desired !== null) {
			desired.normalize();
			desired.mult(this.maxSpeed);
			let steer = p5.Vector.sub(desired, this.velocity);
			steer.limit(this.maxForce);
			this.applyForce(steer);
		}
	}
	
	this.show = function() {
		let angle = this.velocity.heading() + PI / 2;
		
		push();
		translate(this.position.x, this.position.y);
		rotate(angle);
				
		noFill();
		strokeWeight(1);
		stroke(0, 255, 0);
		if(config.show_food_attraction) line(0, 0, 0, -this.dna[0] * 20);
		if(config.show_food_perception) ellipse(0, 0, this.dna[2] * 2);
		
		strokeWeight(1);
		stroke(255, 0, 0);
		if(config.show_poison_repulsion) line(0, 0, 0, this.dna[1] * 20);
		if(config.show_poison_perception) ellipse(0, 0, this.dna[3] * 2);
		
		let green = color(0, 255, 0);
		let red = color(255, 0, 0);
		let col = lerpColor(red, green, this.health);
		
		fill(col);
		stroke(col);
		beginShape();
		vertex(0, -this.r * 2);
		vertex(-this.r, this.r * 2);
		vertex(this.r, this.r * 2);
		endShape(CLOSE);
		
		pop();
	}	
}

function setup() {	
	createCanvas(window.innerWidth, window.innerHeight);	
	
	generateFood(100);
	generatePoison(100);
	generateAgents(10);
	
	elements.generation.innerHTML = stats.generation;
}

function generateAgents(amount) {
	for(let i=0;i<amount;i++) {
		let x = random(config.deadzone, width - config.deadzone);
		let y = random(config.deadzone, height - config.deadzone);
		agents.push(new SteeringAgent(x, y, i));
	}
}

function generateFood(amount) {	
	for(let i=0;i<amount;i++) {
		let x = random(config.deadzone, width - config.deadzone);
		let y = random(config.deadzone, height - config.deadzone);
		food.push(createVector(x, y));
	}
}

function generatePoison(amount) {
	for(let i=0;i<amount;i++) {
		let x = random(config.deadzone, width - config.deadzone);
		let y = random(config.deadzone, height - config.deadzone);
		poison.push(createVector(x, y));
	}
}

function draw() {
	background(51);	
	
	// Spawn new generation(s).
	if(agents.length === 0) {
		generateAgents(10);
		stats.generation++;
		elements.generation.innerHTML = stats.generation;
	}
	
	// Add random food & poison
	if(random(1) < 0.1) generateFood(1);	
	if(random(1) < 0.01) generatePoison(1);
	
	for(let i=0;i<food.length;i++) {
		fill(0, 255, 0);
		noStroke();
		ellipse(food[i].x, food[i].y, 4, 4);
	}
	
	for(let i=0;i<poison.length;i++) {
		fill(255, 0, 0);
		noStroke();
		ellipse(poison[i].x, poison[i].y, 4, 4);
	}
	
	
	for(let i=agents.length-1;i>=0;i--) {
		let agent = agents[i];
		if(agent) {
			agent.boundaries();
			agent.behaviors(food, poison);
			agent.update();
			agent.show();

			let child = agent.clone();
			if(child != null) agents.push(child);

			if(agent.dead()) {
				agents.splice(i, 1);
			}
		}
	}
	
	let dz = config.deadzone;
	strokeWeight(1);
	stroke(20, 20, 20);
	line(dz, dz, dz, height - (dz));
	line(dz, dz, width - (dz), dz);
	line(width-(dz), height-(dz), dz, height-(dz));
	line(width-(dz), dz, width-(dz), height-(dz));
}



(() => {
	let mouseDown = false;
	document.onmousedown = e => { mouseDown = true; }
	document.onmouseup = e => { mouseDown = false; }
	document.onmousemove = e => {
		if(mouseDown) {
			if(e.target.tagName == 'CANVAS')	
				agents.push(new SteeringAgent(e.clientX, e.clientY, agents.length));
		}
	}
	
	
	elements.generation = document.getElementById('generation');
	
	let tools_element = document.querySelector('.tools');
	let toggle_tools_btn = document.querySelector('.toggle_tools_btn');
		
	toggle_tools_btn.addEventListener('click', e => {
		let state = e.currentTarget.getAttribute('state');
		if(state == 'invisible') {
			e.currentTarget.setAttribute('state', 'visible');
			e.currentTarget.className = "toggle_tools_btn visible";
			tools_element.className = 'tools visible';
		} else {
			e.currentTarget.setAttribute('state', 'invisible');
			e.currentTarget.className = "toggle_tools_btn";
			tools_element.className = 'tools';
		}
	});
	
	// Food perception debug handler.
	let show_food_perception_checkbox = document.querySelector('#show_food_perception_checkbox');
	show_food_perception_checkbox.addEventListener('change', e => {
		if(e.currentTarget.checked) config.show_food_perception = true;
		else config.show_food_perception = false;
	});
	
	// Food attraction debug handler.
	let show_food_attraction_checkbox = document.querySelector('#show_food_attraction_checkbox');
	show_food_attraction_checkbox.addEventListener('change', e => {
		if(e.currentTarget.checked) config.show_food_attraction = true;
		else config.show_food_attraction = false;
	});
	
	// Poison perception debug handler.
	let show_poison_perception_checkbox = document.querySelector('#show_poison_perception_checkbox');
	show_poison_perception_checkbox.addEventListener('change', e => {
		if(e.currentTarget.checked) config.show_poison_perception = true;
		else config.show_poison_perception = false;
	});
	
	// Poison repulsion debug handler.
	let show_poison_repulsion_checkbox = document.querySelector('#show_poison_repulsion_checkbox');
	show_poison_repulsion_checkbox.addEventListener('change', e => {
		if(e.currentTarget.checked) config.show_poison_repulsion = true;
		else config.show_poison_repulsion = false;
	});
	
	// Toggle all debug handler.
	let toggle_all_checkbox = document.querySelector('#toggle_all_checkbox');
	toggle_all_checkbox.addEventListener('change', e => {
		if(e.currentTarget.checked) {
			show_food_attraction_checkbox.checked = true;
			show_food_perception_checkbox.checked = true;
			show_poison_repulsion_checkbox.checked = true;
			show_poison_perception_checkbox.checked = true;
			config.show_food_attraction = true;
			config.show_food_perception = true;
			config.show_poison_repulsion = true;
			config.show_poison_perception = true;
		} else {
			show_food_attraction_checkbox.checked = false;
			show_food_perception_checkbox.checked = false;
			show_poison_repulsion_checkbox.checked = false;
			show_poison_perception_checkbox.checked = false;
			config.show_food_attraction = false;
			config.show_food_perception = false;
			config.show_poison_repulsion = false;
			config.show_poison_perception = false;
		}
	});
	
})();
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console