Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

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.

Behavior

Auto Save

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.10/p5.js"></script>
              
            
!

CSS

              
                body {
  padding: 0;
  margin: 0;
  background-color: #FFFFFF;
}
              
            
!

JS

              
                /* This World has carnivore predators, erbivore preys and plants.
Preys need to eat plants to survive and escape form predators; predators hunt preys in order to eat, as they are allergic to plants. The longer they survive
the more likely preys are to reproduce. The more preys predators capture, the more new pradators will come to join the hunt in this world.
When preys die, a plant is left behind.

Press mouse to add new preys to the World.
Press spacebar to add new predators.

// based on Daniel Shiffman http://natureofcode.com/ Evolutionary Computing
*/

var world;

function setup() {
  createCanvas(windowWidth, windowHeight);
  // World starts with 20 creatures
  // and 20 pieces of food
  world = new World(20);
}

function draw() {
  background(51);
  world.run();
}

// We can add a prey manually if we so desire
function mousePressed() {
  world.born(mouseX, mouseY);
}

// We can also add an hunter by pressing spacebar
function keyPressed() {
  if (key  == " ") {
    world.hunt(random(width), random(height));
  }
}


// my Vehicle class

// Create my Vehicle
function Vehicle(l, dna_, identity) {
  this.pos = l.copy(); // Location
  this.vel = createVector(0, 0); // Velocity
  this.acc = createVector(0, 0); // Acceleration
  this.health = 200; // Life timer
  this.xoff = random(1000); // For perlin noise
  this.yoff = random(1000);
  this.dna = dna_; // DNA
  this.getKilled = false;
  this.isWandering = true;
  this.r = 6;
  // DNA will determine phenotype: maxspeed and maxforce
  this.maxspeed = map(this.dna.genes[0], 0, 1, 0.8, 4.8);
  this.maxforce = map(this.dna.genes[0], 0, 1, 0.2, 0.5);
  //this.r = map(this.dna.genes[0], 0, 1, 0, 50);
  this.identity = identity; // determines the status of each veicle: "hunter" or "prey"
  this.alertRange = 150; // if you are that close the hunt starts
  this.killRange = 10; // ouch! if you get this close you get killed

  this.checkdistance = function(otherVehicle) { // here we switch behaviours based on vehicle's proximity
    var desired = p5.Vector.sub(otherVehicle.pos, this.pos);
    var d = desired.mag();
    if (!this.getKilled && this.identity === "prey" && otherVehicle.identity === "hunter") {
      if (d < this.killRange) {
        //print("I got you");
        this.getKilled = true;
        otherVehicle.health += 100; // the hunter eats its prey and gain health
        otherVehicle.calcFitness(); // the hunter eats and gets its chance to join the hunt
      } else if (d < this.alertRange) {
        otherVehicle.isWandering = false;
        otherVehicle.seek(this);
        this.isWandering = false;
        this.flee(otherVehicle);
      } else {
        //Just wandering: simple movement based on perlin noise
        this.isWandering = true;
        //this.wander();
        //otherVehicle.wander();
      }
    }
  }

  this.seek = function(target) {
    var desired = p5.Vector.sub(target.pos, this.pos);
    desired.setMag(this.maxspeed);
    var steering = p5.Vector.sub(desired, this.vel);
    steering.limit(this.maxforce);
    this.applyForce(steering);
  }

  this.flee = function(target) {
    var desired = p5.Vector.sub(this.pos, target.pos);
    desired.setMag(this.maxspeed);
    var steering = p5.Vector.sub(desired, this.vel);
    steering.limit(this.maxforce);
    this.applyForce(steering);
  }

  this.wander = function() {
    var noisyangle = map(noise(this.xoff), 0, 1, 0, TWO_PI);
    var wandering = p5.Vector.fromAngle(noisyangle);
    wandering.setMag(this.maxspeed);
    var steering = p5.Vector.sub(wandering, this.vel);
    //steering.limit(0.02);
    this.applyForce(steering);
    this.xoff += 0.02;
  }

  this.run = function() {
    this.update();
    this.wrapAround();
    this.display();

    if (this.isWandering) {
      this.wander();
    } else {
      //do nothing
    }
  }

  // A prey can find food and eat it to gain health
  // A hunter gets fat eating food this has health consequences
  this.eat = function(f) {
    var food = f.getFood();
    // Are we touching any food objects?
    for (var i = food.length - 1; i >= 0; i--) {
      var foodLocation = food[i];
      var d = p5.Vector.dist(this.pos, foodLocation);
      // If we are, juice up our strength and speed!
      if (d < this.r) {
        if (this.identity === "prey") {
          this.health += 100;
          food.splice(i, 1);
        } else if (this.identity === "hunter") {
          this.health -= 60;
          food.splice(i, 1);
        }
      }
    }
  }

  // At any moment there is a teeny, tiny chance a prey will reproduce
  this.reproduce = function() {
    // asexual reproduction //optimal rate 0.0005
    if (random(1) < 0.0005) {
      // Child is exact copy of single parent
      print("it's a prey!");
      var childDNA = this.dna.copy();
      // Child DNA can mutate
      childDNA.mutate(0.01);
      return new Vehicle(this.pos, childDNA, "prey");
    } else {
      return null;
    }
  }

  // if the hunter eat a prey, there is a chance a new hunter will join the hunt
  this.calcFitness = function() {
    if (random(1) < 0.4) {
      print("a new hunter has joined the hunt!");
      var childDNA = this.dna.copy();
      childDNA.mutate(0.01);
      var hpos = createVector(random(width), random(height));
      //var hpos = createVector(width / 2, height / 2);
      return new Vehicle(hpos, childDNA, "hunter");
    } else {
      return null;
    }
  }

  this.applyForce = function(force) {
    this.acc.add(force);
  }

  // Method to update position
  this.update = function() {
    /* Simple movement based on perlin noise
    var vx = map(noise(this.xoff), 0, 1, -this.maxspeed, this.maxspeed);
    var vy = map(noise(this.yoff), 0, 1, -this.maxspeed, this.maxspeed);
    var velocity = createVector(vx, vy);
    this.xoff += 0.01;
    this.yoff += 0.01;
    this.pos.add(velocity);
    */
    this.vel.add(this.acc);
    this.vel.limit(this.maxspeed);
    this.pos.add(this.vel);
    this.acc.set(0, 0);
    // Death always looming
    this.health -= 0.2;
  }

  // Wraparound
  this.wrapAround = function() {
    if (this.pos.x < -this.r) this.pos.x = width + this.r;
    if (this.pos.y < -this.r) this.pos.y = height + this.r;
    if (this.pos.x > width + this.r) this.pos.x = -this.r;
    if (this.pos.y > height + this.r) this.pos.y = -this.r;
  }

  // Method to display //
  this.display = function() {
    // Draw a triangle rotated in the direction of velocity
    var theta = this.vel.heading() + PI / 2;
    if (this.identity === "prey") {
      fill(255, this.health); // white preys
    } else if (this.identity === "hunter") {
      fill(255, 0, 0, this.health); // red hunters
    } else {
      fill(0);
    }
    noStroke();
    push();
    translate(this.pos.x, this.pos.y);
    rotate(theta);
    beginShape();
    vertex(0, -this.r * 2);
    vertex(-this.r, this.r * 2);
    vertex(this.r, this.r * 2);
    endShape(CLOSE);
    pop();
  }

  // Death
  this.dead = function() {
    if (this.health < 0.0) {
      return true;
    } else {
      return false;
    }
  }
}

// The World we live in has carnivore predators, erbivore preys and plants

// Constructor
function World(num) {
  // Start with initial food and creatures
  this.food = new Food(num);
  this.identity;
  this.population = []; // An array for all vehicles
  //make a new set of creatures
  for (var i = 0; i < num; i++) {
    if (random(1) >= 0.9) {
      this.identity = "hunter";
      //counter++;
    } else {
      this.identity = "prey";
    }
    var l = createVector(random(width), random(height));
    var dna = new DNA();
    this.population.push(new Vehicle(l, dna, this.identity)); // populating the array with my creatures.
  }


  // Make a new prey
  this.born = function(x, y) {
    var l = createVector(x, y);
    var dna = new DNA();
    this.population.push(new Vehicle(l, dna, "prey"));
  }

  // Make a new hunt
  this.hunt = function(x, y) {
    var l = createVector(x, y);
    var dna = new DNA();
    this.population.push(new Vehicle(l, dna, "hunter"));
  }

  // Run the world
  this.run = function() {
    // Deal with food
    this.food.run();

    // Cycle through the ArrayList backwards b/c we are deleting
    for (var i = this.population.length - 1; i >= 0; i--) {
      // All population run and eat
      var b = this.population[i];
      b.run();
      b.eat(this.food);
      for (var j = this.population.length - 1; j >= 0; j--) {
        if (i != j) {
          this.population[i].checkdistance(this.population[j]);
        }
      }
      // If it's dead, kill it and make food
      if (b.dead()) {
        this.population.splice(i, 1);
        this.food.add(b.pos);
      }
      // If a prey gets killed by an hunter, probably more hunters will come
      if (b.getKilled == true) {
        this.population.splice(i, 1);
        this.food.add(b.pos);
        var hunt = b.calcFitness();
        if (hunt != null) this.population.push(hunt);
      }
      if (b.identity === "prey") {
        // Perhaps this prey would like to make a baby?
        var child = b.reproduce();
        if (child != null) this.population.push(child);
      }
    }
  }
}

// A collection of food in the world

function Food(num) {
  // Start with some food
  this.food = [];
  for (var i = 0; i < num; i++) {
     this.food.push(createVector(random(width),random(height)));
  }

  // Add some food at a location
  this.add = function(l) {
     this.food.push(l.copy());
  }

  // Display the food
  this.run = function() {
    for (var i = 0; i < this.food.length; i++) {
      var f = this.food[i];
      push();
      rectMode(CENTER);
      noStroke();
      fill(25, 200, 0);
      translate(f.x,f.y);
      rotate(PI/3.0);
      rect(0,0,8,8);
      pop();
    }

    // There's a small chance food will appear randomly
    if (random(1) < 0.001) {
       this.food.push(createVector(random(width),random(height)));
    }
  }

  // Return the list of food
  this.getFood = function() {
    return this.food;
  }
}

// Constructor (makes a random DNA)
function DNA(newgenes) {
  if (newgenes) {
    this.genes = newgenes;
  } else {
    // The genetic sequence
    // DNA is random floating point values between 0 and 1 (!!)
    this.genes = new Array(1);
    for (var i = 0; i < this.genes.length; i++) {
      this.genes[i] = random(0,1);
    }
  }

  this.copy = function() {
    // should switch to fancy JS array copy
    var newgenes = [];
    for (var i = 0; i < this.genes.length; i++) {
      newgenes[i] = this.genes[i];
    }

    return new DNA(newgenes);
  }

  // Based on a mutation probability, picks a new random character in array spots
  this.mutate = function(m) {
    for (var i = 0; i < this.genes.length; i++) {
      if (random(1) < m) {
         this.genes[i] = random(0,1);
      }
    }
  }
}


              
            
!
999px

Console