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.

            
              <div id="start-screen">
  <h1>Slither Snake</h1>
  <div class="flexcontainer">
    <div class="row">
      <div class="instructions">
        <img src="https://res.cloudinary.com/dkw0kkkgd/image/upload/v1481315302/Arrow-keys_utpewf.jpg" height="60" width="92">
      </div>
      <div class="instructions">Use the arrow keys to change the snake's direction</div>
    </div>
    <div class="row">
      <div class="instructions">Don't run into your own tail</div>
      <div class="instructions">
        <img src="https://res.cloudinary.com/dkw0kkkgd/image/upload/v1481315307/Screen_Shot_2016-12-09_at_2.22.49_PM_f5yqz4.png" height="90" width="174">
      </div>
    </div>
    <div class="row">
      <div class="instructions">
        <img src="https://res.cloudinary.com/dkw0kkkgd/image/upload/v1481315311/Screen_Shot_2016-12-09_at_2.24.33_PM_ghqncx.png" height="90" width="190">
      </div>
      <div class="instructions">Don't run into the walls</div>
    </div>
    <div class="row">
      <div class="instructions">Eat the red dots to grow and increase your score</div>
      <div class="instructions">
        <img src="https://res.cloudinary.com/dkw0kkkgd/image/upload/v1481315317/Screen_Shot_2016-12-09_at_2.25.12_PM_xocpi7.png" height="40" width="48">
      </div>
    </div>
  </div>
  <button>Play</button>
</div>
            
          
!
            
              html {
  text-align: center;
}

canvas {
  margin-top: 10px;
  border: 1px solid gray;
}

.flexcontainer {
   display: -webkit-flex;
   display: flex;
   -webkit-flex-direction: column;
   flex-direction: column;
   width: 555px;
   margin: 0 auto;
   margin-top: 10px;
}

div {
  vertical-align: middle;
}

.instructions {
  display: inline-block;
  margin: 10px 20px;
  width: 200px;
}

.row:not(:last-child) {
  width: 100%;
  border-bottom: 1px solid lightgrey;
}

body,
h1 {
  margin: 0;
  padding: 0;
}

ul {
  list-style-type: none;
}

button {
  margin-top: 10px;
  cursor: pointer;
  font-size: 24px;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
}

button:hover {
  background: #A0A0A0;
}

#start-screen {
  font-family: 'Roboto', sans-serif;
  text-align: center;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 99999;
  background: white;
}

h1 {
  background: #9999a1;
  padding: 5px;
  color: white;
}
            
          
!
            
              var food;
var foodDiameter = 24;
var ghost;
var s;
var tailLength = 50;
var snakeSize = 32;
var gamePaused = true;
var highScore = 50;

if (localStorage.getItem("_highScore") === null) {
  localStorage._highScore = highScore;
}

function setup() {
  var iHeight = window.innerHeight <= 542 ? window.innerHeight - 20 : 522;
  var iWidth = window.innerWidth <= 957 ? window.innerWidth - 20 : 937;
  createCanvas(iWidth, iHeight);
  
  s = new Snake(width/4, height/2);
  // snake will chase an invisible ghost to steer
  ghost = new Ghost();
  pickLocation();
  var button = select('button');
  var startScreen = select('#start-screen');
  button.mouseClicked(function() {
    startScreen.hide();
    gamePaused = false;
  });
}

function draw() {
  background(245, 248, 250);
  noStroke();
  fill(54);
  textSize(16);
  text("tail length: " + tailLength, width/8, 30);
  text("high score: " + localStorage.getItem("_highScore"), width/8, 60);
  
  if (!gamePaused) {
    ghost.update();
    ghost.show();

    var ghostVect = createVector(ghost.x, ghost.y);

    if (s.eat(food)) {
      if (tailLength > localStorage.getItem("_highScore")) {
        localStorage._highScore = tailLength;
      }
      pickLocation();
    }

    // snake follows the ghost to steer
    s.seek(ghostVect);
    s.update();
    s.death();
  }
  s.display();
  
  fill(255, 0, 100);
  ellipse(food.x, food.y, foodDiameter, foodDiameter);

}

function pickLocation() {
  var offset = 40;
  food = createVector(random(offset, width - offset), random(offset, height - offset));
}

function keyPressed() {
  var ghostX = ghost.xspeed;
  var ghostY = ghost.yspeed;
  if (keyCode === UP_ARROW) {
    if (ghostY < 1) {
      ghost.dir(0, -1);
    }
  } else if (keyCode === DOWN_ARROW) {
    if (ghostY > -1) {
      ghost.dir(0, 1);
    }
  } else if (keyCode === RIGHT_ARROW) {
    if (ghostX > -1) {
      ghost.dir(1, 0);
    }
  } else if (keyCode === LEFT_ARROW) {
    if (ghostX < 1) {
      ghost.dir(-1, 0);
    }
  }
}

function Snake(x,y) {
  this.acceleration = createVector(0,0);
  this.velocity = createVector(0,0);
  this.position = createVector(x,y);
  this.r = snakeSize;
  this.maxspeed = 3;
  this.maxforce = 0.2;
  this.history = [];
  this.eatingVal = 0;

  // Method to update location
  this.update = function() {
        var v = createVector(this.position.x,this.position.y);
    this.history.push(v);
    
    if (this.history.length > tailLength) {
        this.history.splice(0,1);   
    }
    // Update velocity
    this.velocity.add(this.acceleration);
    // Limit speed
    this.velocity.limit(this.maxspeed);
    this.position.add(this.velocity);
    // Reset accelerationelertion to 0 each cycle
    this.acceleration.mult(0);
    
    if (this.eatingVal > 0) {
      this.eatingVal -= 0.5;
    }
  };

  this.applyForce = function(force) {
    // We could add mass here if we want A = F / M
    this.acceleration.add(force);
  };

  // A method that calculates a steering force towards a target
  // STEER = DESIRED MINUS VELOCITY
  this.seek = function(target) {

    var desired = p5.Vector.sub(target,this.position);  // A vector pointing from the location to the target

    // Scale to maximum speed
    desired.setMag(this.maxspeed);

    // Steering = Desired minus velocity
    var steer = p5.Vector.sub(desired,this.velocity);
    steer.limit(this.maxforce);  // Limit to maximum steering force

    this.applyForce(steer);
  };
  
  this.reset = function() {
    gamePaused = true;
    var that = this;
    this.history.forEach(function(seg) {
      seg.add(random(-10, 10), random(-10, 10));
    });
    setTimeout(function() {
      tailLength = 50;
      that.history = [];
      that.position = createVector(width/2, height/2);
      gamePaused = false;
    }, 3000);
  }
  
  this.death = function() {
    var offset = this.r/2;
    var outOfBoundsX = this.position.x < offset || this.position.x > width - offset;
    var outOfBoundsY = this.position.y < offset || this.position.y > height - offset;
    if (outOfBoundsX || outOfBoundsY) {
      this.reset();
    } else {
      for (var i = 0; i < this.history.length - 10; i++) {
        var pos = this.history[i];
        var d = dist(this.position.x, this.position.y, pos.x, pos.y);
        if (d < 2) {
          this.reset();
        }
      }
    }
  }
  
  this.eat = function(pos) {
    var d = dist(this.position.x, this.position.y, pos.x, pos.y);
    if (d < foodDiameter) {
      tailLength += 20;
      this.eatingVal = 20;
      return true;
    } else {
      return false;
    }
  }

  this.display = function() {
    // Draw a snake rotated in the direction of velocity
    var theta = this.velocity.heading() + PI/2;
    fill(0,150,150);
    noStroke();
    for (var i = 0; i < this.history.length; i++) {
      var pos = this.history[i];
      var size = map(i,0,this.history.length,5,this.r);
      ellipse(pos.x, pos.y, size, size);
    } 
    fill(0,150,150);
    ellipse(this.x,this.y,this.r,this.r);
    push();
    translate(this.position.x,this.position.y);
    rotate(theta);
    fill(0,210,150);
    ellipse(0, -this.eatingVal, this.r, this.r);
    fill(255, 0, 0);
    rect(-2, -2 * this.eatingVal, 4, 15);
    stroke(0);
    fill(255);
    triangle(-10, -20, -10, 0, 0, 0);
    triangle(10, -20, 10, 0, 0, 0);
    fill(0,150,150);
    noStroke();
    ellipse(0, 0, this.r, this.r);
    if (!gamePaused) {
      fill(255);
      ellipse(-this.r/5, 0, 12, 12);
      ellipse(this.r/5, 0, 12, 12);
      fill(98);
      ellipse(-this.r/5, 0, 6, 6);
      ellipse(this.r/5, 0, 6, 6);
    } else {
      fill(255);
      textSize(12);
      text("X", -this.r/4 - 1, 0);
      text("X", 1, 0);
    }
    pop();
  };
}

function Ghost() {
  this.x = 0;
  this.y = width/2;
  this.xspeed = 5;
  this.yspeed = 0;

  this.dir = function(x, y) {
    this.xspeed = x * 5;
    this.yspeed = y * 5;
  }

  this.update = function() {

    this.x = this.x + this.xspeed;
    this.y = this.y + this.yspeed;

    this.x = constrain(this.x, 0, width - 20);
    this.y = constrain(this.y, 0, height - 20);
  }

  this.show = function() {
    fill(255, 0);
    noStroke();
    rect(this.x, this.y, 20, 20);
  }
}
            
          
!
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