HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URL's added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div id="container"></div>
@import "bourbon";
body{
background-color: #222;
}
var calculateDistance = function(object1, object2){
x = Math.abs(object1.x - object2.x);
y = Math.abs(object1.y - object2.y);
return Math.sqrt((x * x) + (y * y));
};
var calcMagnitude = function(x, y) {
return Math.sqrt((x * x) + (y * y));
};
var calcVectorAdd = function(v1, v2) {
return {x: v1.x + v2.x, y: v1.y + v2.y};
};
var random = function( min, max ) {
return min + Math.random() * ( max - min );
};
var getRandomItem = function(list, weight) {
var total_weight = weight.reduce(function (prev, cur, i, arr) {
return prev + cur;
});
var random_num = random(0, total_weight);
var weight_sum = 0;
//console.log(random_num)
for (var i = 0; i < list.length; i++) {
weight_sum += weight[i];
weight_sum = +weight_sum.toFixed(2);
if (random_num <= weight_sum) {
return list[i];
}
}
// end of function
};
/***********************
BOID
***********************/
function Boid(x, y) {
this.init(x, y);
}
Boid.prototype = {
init: function(x, y) {
//body
this.type = "boid";
this.alive = true;
this.health = 1;
this.maturity = 4;
this.speed = 6;
this.size = 5;
this.hungerLimit = 12000;
this.hunger = 0;
this.isFull = false;
this.digestTime = 400;
this.color = 'rgb(' + ~~random(0,100) + ',' + ~~random(50,220) + ',' + ~~random(50,220) + ')';
//brains
this.eyesight = 100; //range for object dectection
this.personalSpace = 20; //distance to avoid safe objects
this.flightDistance = 60; //distance to avoid scary objects
this.flockDistance = 100; //factor that determines how attracted the boid is to the center of the flock
this.matchVelFactor = 6; //factor that determines how much the flock velocity affects the boid. less = more matching
this.x = x || 0.0;
this.y = y || 0.0;
this.v = {
x: random(-1, 1),
y: random(-1, 1),
mag: 0
};
this.unitV = {
x: 0,
y: 0,
};
this.v.mag = calcMagnitude(this.v.x, this.v.y);
this.unitV.x = (this.v.x / this.v.mag);
this.unitV.y = (this.v.y / this.v.mag);
},
wallAvoid: function(ctx) {
var wallPad = 10;
if (this.x < wallPad) {
this.v.x = this.speed;
} else if (this.x > ctx.width - wallPad) {
this.v.x = -this.speed;
}
if (this.y < wallPad) {
this.v.y = this.speed;
} else if (this.y > ctx.height - wallPad) {
this.v.y = -this.speed;
}
},
ai: function(boids, index, ctx) {
percievedCenter = {
x: 0,
y: 0,
count: 0
};
percievedVelocity = {
x: 0,
y: 0,
count: 0
};
mousePredator = {
x: ((typeof ctx.touches[0] === "undefined") ? 0 : ctx.touches[0].x),
y: ((typeof ctx.touches[0] === "undefined") ? 0 : ctx.touches[0].y)
};
for (var i = 0; i < boids.length; i++) {
if (i != index) {
dist = calculateDistance(this, boids[i]);
//Find all other boids close to it
if (dist < this.eyesight) {
//if the same species then flock
if (boids[i].type == this.type) {
//Alignment
percievedCenter.x += boids[i].x;
percievedCenter.y += boids[i].y;
percievedCenter.count++;
//Cohesion
percievedVelocity.x += boids[i].v.x;
percievedVelocity.y += boids[i].v.y;
percievedVelocity.count++;
//Separation
if (dist < this.personalSpace + this.size + this.health) {
this.avoidOrAttract("avoid", boids[i]);
}
} else {
//if other species fight or flight
if (dist < this.size + this.health + boids[i].size + boids[i].health) {
this.eat(boids[i]);
} else {
this.handleOther(boids[i]);
}
}
}//if close enough
}//dont check itself
}//Loop through boids
//Get the average for all near boids
if (percievedCenter.count > 0) {
percievedCenter.x = ((percievedCenter.x / percievedCenter.count) - this.x) / this.flockDistance;
percievedCenter.y = ((percievedCenter.y / percievedCenter.count) - this.y) / this.flockDistance;
this.v = calcVectorAdd(this.v, percievedCenter);
}
if (percievedVelocity.count > 0) {
percievedVelocity.x = ((percievedVelocity.x / percievedVelocity.count) - this.v.x) / this.matchVelFactor;
percievedVelocity.y = ((percievedVelocity.y / percievedVelocity.count) - this.v.y) / this.matchVelFactor;
this.v = calcVectorAdd(this.v, percievedVelocity);
}
//Avoid Mouse
if (calculateDistance(mousePredator, this) < this.eyesight) {
var mouseModifier = 20;
this.avoidOrAttract("avoid", mousePredator, mouseModifier);
}
this.wallAvoid(ctx);
this.limitVelocity();
},
setUnitVector: function() {
var magnitude = calcMagnitude(this.v.x, this.v.y);
this.v.x = this.v.x / magnitude;
this.v.y = this.v.y / magnitude;
},
limitVelocity: function() {
this.v.mag = calcMagnitude(this.v.x, this.v.y);
this.unitV.x = (this.v.x / this.v.mag);
this.unitV.y = (this.v.y / this.v.mag);
if (this.v.mag > this.speed) {
this.v.x = this.unitV.x * this.speed;
this.v.y = this.unitV.y * this.speed;
}
},
avoidOrAttract: function(action, other, modifier) {
var newVector = {x: 0, y: 0};
var direction = ((action === "avoid") ? -1 : 1);
var vModifier = modifier || 1;
newVector.x += ( (other.x - this.x) * vModifier ) * direction;
newVector.y += ( (other.y - this.y) * vModifier ) * direction;
this.v = calcVectorAdd(this.v, newVector);
},
move: function() {
this.x += this.v.x;
this.y += this.v.y;
if (this.v.mag > this.speed) {
this.hunger += this.speed;
} else {
this.hunger += this.v.mag;
}
},
eat: function(other) {
if (!this.isFull) {
if (other.type === "plant") {
other.health--;
this.health++;
this.isFull = true;
this.hunger = 0;
}
}
},
handleOther: function(other) {
if (other.type === "predator") {
this.avoidOrAttract("avoid", other);
}
},
metabolism: function() {
if (this.hunger >= this.hungerLimit) {
this.health--;
this.hunger = 0;
}
if (this.hunger >= this.digestTime) {
this.isFull = false;
}
if (this.health <= 0) {
this.alive = false;
}
},
mitosis: function(boids) {
if (this.health >= this.maturity) {
//reset old boid
this.health = 1;
birthedBoid = new Boid(
this.x + random(-this.personalSpace, this.personalSpace),
this.y + random(-this.personalSpace, this.personalSpace)
);
birthedBoid.color = this.color;
boids.push(birthedBoid);
}
},
draw: function( ctx ) {
drawSize = this.size + this.health;
ctx.beginPath();
ctx.moveTo( this.x + ( this.unitV.x * drawSize ), this.y + ( this.unitV.y * drawSize ));
ctx.lineTo( this.x + ( this.unitV.y * drawSize ), this.y - ( this.unitV.x * drawSize ));
ctx.lineTo( this.x - ( this.unitV.x * drawSize * 2 ), this.y - ( this.unitV.y * drawSize * 2 ));
ctx.lineTo( this.x - ( this.unitV.y * drawSize ), this.y + ( this.unitV.x * drawSize ));
ctx.lineTo( this.x + ( this.unitV.x * drawSize ), this.y + ( this.unitV.y * drawSize ));
ctx.fillStyle = this.color;
ctx.shadowBlur = 20;
ctx.shadowColor = this.color;
ctx.fill();
}
};
Predator.prototype = new Boid();
Predator.prototype.constructor = Predator;
Predator.constructor = Boid.prototype.constructor;
function Predator(x, y) {
this.init(x, y);
this.type = "predator";
//body
this.maturity = 6;
this.speed = 6;
this.hungerLimit = 25000;
this.color = 'rgb(' + ~~random(100,250) + ',' + ~~random(10,30) + ',' + ~~random(10,30) + ')';
//brains
this.eyesight = 150;
this.flockDistance = 300;
}
Predator.prototype.eat = function(other) {
if (!this.isFull) {
if (other.type === "boid") {
other.health--;
this.health++;
this.isFull = true;
this.hunger = 0;
}
}
};
Predator.prototype.handleOther = function(other) {
if (other.type === "boid") {
if (!this.isFull) {
this.avoidOrAttract("attract", other);
}
}
};
Predator.prototype.mitosis = function(boids) {
if (this.health >= this.maturity) {
//reset old boid
this.health = 1;
birthedBoid = new Predator(
this.x + random(-this.personalSpace, this.personalSpace),
this.y + random(-this.personalSpace, this.personalSpace)
);
birthedBoid.color = this.color;
boids.push(birthedBoid);
}
};
Plant.prototype = new Boid();
Plant.prototype.constructor = Plant;
Plant.constructor = Boid.prototype.constructor;
function Plant(x, y) {
this.init(x, y);
this.type = "plant";
//body
this.speed = 0;
this.size = 10;
this.health = ~~random(1, 10);
this.color = 'rgb(' + ~~random(130,210) + ',' + ~~random(40,140) + ',' + ~~random(160,220) + ')';
//brains
this.eyesight = 0;
this.flockDistance = 0;
this.eyesight = 0; //range for object dectection
this.personalSpace = 100; //distance to avoid safe objects
this.flightDistance = 0; //distance to avoid scary objects
this.flockDistance = 0; //factor that determines how attracted the boid is to the center of the flock
this.matchVelFactor = 0; //factor that determines how much the flock velocity affects the boid
}
Plant.prototype.ai = function(boids, index, ctx) { };
Plant.prototype.move = function() { };
Plant.prototype.mitosis = function(boids) {
var growProbability = 1,
maxPlants = 40,
plantCount = 0;
for ( m = boids.length - 1; m >= 0; m-- ) {
if (boids[m].type === "plant") {
plantCount++;
}
}
if (plantCount <= maxPlants) {
if (random(0,100) <= growProbability) {
birthedBoid = new Plant(
this.x + random(-this.personalSpace, this.personalSpace),
this.y + random(-this.personalSpace, this.personalSpace)
);
birthedBoid.color = this.color;
boids.push(birthedBoid);
}
}
};
Plant.prototype.draw = function(ctx) {
var drawSize = this.size + this.health;
ctx.fillStyle = this.color;
ctx.shadowBlur = 40;
ctx.shadowColor = this.color;
ctx.fillRect(this.x - drawSize, this.y + drawSize, drawSize, drawSize);
};
/***********************
SIM
***********************/
var boids = [];
var sim = Sketch.create({
container: document.getElementById( 'container' )
});
sim.setup = function() {
for ( i = 0; i < 50; i++ ) {
x = random(0, sim.width);
y = random(0, sim.height);
sim.spawn( x, y);
}
};
sim.spawn = function( x, y) {
var predatorProbability = 0.1,
plantProbability = 0.3;
switch(getRandomItem(['boid','predator','plant'],[1 - predatorProbability - plantProbability, predatorProbability, plantProbability])) {
case 'predator':
boid = new Predator(x, y);
break;
case 'plant':
boid = new Plant(x, y);
break;
default:
boid = new Boid(x, y);
break;
}
boids.push( boid );
};
sim.update = function() {
for ( i = boids.length - 1; i >= 0; i-- ) {
if (boids[i].alive) {
boids[i].ai(boids, i, sim);
boids[i].move();
boids[i].metabolism();
boids[i].mitosis(boids);
} else {
//remove dead boid
boids.splice(i,1);
}
}
};
sim.draw = function() {
sim.globalCompositeOperation = 'lighter';
for ( i = boids.length - 1; i >= 0; i-- ) {
boids[i].draw( sim );
}
sim.fillText(boids.length, 20, 20);
};
Also see: Tab Triggers