123

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              *
  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++;
    }
}

            
          
!
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.

Console