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 URLs 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 its URL and the proper URL extension.
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 esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM 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.
*
box-sizing: border-box
body
padding: 0
margin: 0
background-color: #333
color: #fff
font-family: 'Roboto', arial
canvas
border: 2px solid white
margin: 20px auto
display: block
p
margin: 10px auto
width: 640px // same as the canvas just to align it
class DNA {
constructor(lifeSpan) {
this.genes = [];
this.lifeSpan = lifeSpan;
// Populate the new DNA object with some fresh new genes
for (let i = 0; i < lifeSpan; i++) {
this.genes[i] = p5.Vector.random2D();
this.genes[i].setMag(0.3);
}
}
// The crossover() will take care of merging the parents's DNA
crossover(partner) {
let newDNA = new DNA(this.lifeSpan);
let midPoint = floor(random(this.genes.length));
// We pick a point in the genes
// We will create the first half of the child DNA from the genes BEFORE the midpoint
// And the second half from the rest of parentB DNA
for (let i = 0; i < this.genes.length; i++) {
if (i > midPoint) {
newDNA.genes[i] = this.genes[i];
} else {
newDNA.genes[i] = partner.genes[i];
}
}
return newDNA;
}
// The mutation() will take care of causing minor and random changes on the genes
mutation() {
for (let i = 0; i < this.genes.length; i++) {
if (random(1) < 0.01) {
this.genes[i] = p5.Vector.random2D();
this.genes[i].setMag(0.3);
}
}
}
}
class Rocket {
constructor(lifeSpan, target, obstacle, childDNA) {
this.pos = createVector(width / 2, height - 50);
this.w = 5;
this.h = 10;
this.color = [255, 255, 255];
this.vel = createVector();
this.acc = createVector();
if (childDNA) {
this.dna = childDNA;
} else {
this.dna = new DNA(lifeSpan);
}
this.count = 0;
this.target = target;
this.obstacle = obstacle;
this.fitness = 0;
this.completed = false;
this.crashed = false;
}
applyForce(f) {
this.acc.add(f);
}
update() {
let d = dist(this.pos.x, this.pos.y, this.target.x, this.target.y);
// If the rocket the close enough then its reached its goal
if (d < 10) {
this.completed = true;
this.pos = this.target.copy();
this.color = [46, 204, 113];
}
// Check if the rocket hit the obstacle
if (
this.pos.x > this.obstacle.pos.x &&
this.pos.x < this.obstacle.pos.x + this.obstacle.w &&
this.pos.y > this.obstacle.pos.y &&
this.pos.y < this.obstacle.pos.y + this.obstacle.h
) {
this.crashed = true;
this.color = [231, 76, 60];
}
// Check if the rocket hit the world edges
if (this.pos.x > width || this.pos.x < 0) {
this.crashed = true;
this.color = [231, 76, 60];
}
if (this.pos.y > height || this.pos.y < 0) {
this.crashed = true;
this.color = [231, 76, 60];
}
// Apply the moving forces of the rocket "thrusters"
this.applyForce(this.dna.genes[this.count]);
this.count++;
// Only move if the rocket didn't reach it goal
if (!this.completed && !this.crashed) {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
this.vel.limit(4);
}
}
show() {
push();
noStroke();
fill(...this.color, 150);
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
rectMode(CENTER);
// the rocket body
rect(0, 0, 10, 5);
// this tip
triangle(
this.h / 2,
-this.w / 2,
this.h / 2,
this.w / 2,
this.h,
0
);
pop();
}
calcFitness() {
// Calculating the based on how much the rocket got close to the target
let d = dist(this.pos.x, this.pos.y, this.target.x, this.target.y);
this.fitness = map(d, 0, width, width, 0);
if (this.completed) {
this.fitness *= 10;
}
if (this.crashed) {
this.fitness /= 10;
}
}
}
class Population {
constructor(populationSize, lifeSpan, target, obstacle) {
this.rockets = [];
this.populationSize = populationSize;
this.matingPool = [];
// Populate the new population with some fresh new Rockets
for (let i = 0; i < this.populationSize; i++) {
this.rockets[i] = new Rocket(lifeSpan, target, obstacle);
}
}
evaluate() {
// Get the best rocket based on its fitness
let maxFit = 0;
for (let i = 0; i < this.populationSize; i++) {
this.rockets[i].calcFitness();
if (this.rockets[i].fitness > maxFit) {
maxFit = this.rockets[i].fitness;
}
}
console.clear();
console.log(`Best fitness reached is: ${maxFit}`);
for (let i = 0; i < this.populationSize; i++) {
// Normalizing the fitness value to be in the range between 0 and 1
this.rockets[i].fitness /= maxFit;
}
// Resting the mating pool
this.matingPool = [];
// We want to increase the possibility of picking a rocket as parent to be related with how good its fitness
// So if it has a fitness of 1 it will be in the mating pool 100 times
// And if it has a fitness of 0.1 it will be in the mating pool only 10 times which will decrease its chances of being picked
for (let i = 0; i < this.populationSize; i++) {
let n = this.rockets[i].fitness * 100;
for (let j = 0; j < n; j++) {
this.matingPool.push(this.rockets[i]);
}
}
}
selection() {
let newRockets = [];
for (let i = 0; i < this.rockets.length; i++) {
// Get two random parents from the mating pool and make a crossover
let parentA = random(this.matingPool).dna;
let parentB = random(this.matingPool).dna;
let childDNA = parentA.crossover(parentB);
// Apply some mutations to the child
childDNA.mutation();
// Replacing each rocket from the old generation with a new rocket
newRockets[i] = new Rocket(
this.rockets[i].lifeSpan,
this.rockets[i].target,
obstacle,
childDNA
);
}
// Replace old rockets array with the new one
this.rockets = newRockets;
}
run() {
for (let i = 0; i < this.populationSize; i++) {
this.rockets[i].update();
this.rockets[i].show();
}
}
}
class Block {
constructor(x, y, w, h) {
this.pos = createVector(x, y);
this.w = w;
this.h = h;
}
show() {
noStroke();
rect(this.pos.x, this.pos.y, this.w, this.h);
}
}
// Init app
let population;
let lifeSpan = 450;
let lifeP;
let currentGenerationNumber = 0;
let pastGnerationsCounter = 1;
let target;
let obstacle;
let x = 20;
let y = 20;
function setup() {
createCanvas(640, 480);
// Init target and the obstacle
target = createVector(width / 2, 50);
obstacle = new Block(width / 2 - 75, height / 2, 150, 10);
population = new Population(25, lifeSpan, target, obstacle);
lifeP = createP();
}
function draw() {
background(55);
lifeP.html(`Generation #${pastGnerationsCounter}`);
currentGenerationNumber++;
// Obstacle
obstacle.show();
// Show the target
ellipse(target.x, target.y, 16);
// Kickstart the population
population.run();
// If we reached the end of a generation life span
if (currentGenerationNumber === lifeSpan) {
// Evaluate stuff and generate new generation
population.evaluate();
population.selection();
currentGenerationNumber = 0;
pastGnerationsCounter++;
}
}
Also see: Tab Triggers