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="scoreboard">
	<div class="inline">Score: <div class="inline" id="score">0</div></div>
  <div class="inline">High Score: <div class="inline" id="highScore">0</div></div>
</div>
            
          
!
            
              * {
  margin: 0;
  padding: 0; }
    
body { 
  overflow: hidden;
  text-align: center;
  background-color: #666; }
    
.inline {
  margin: 6px;
  display: inline-block; }
            
          
!
            
              //global variables //global variables //global variables //global variables //global variables
var dimensions = 600;
var skale = 40;
var snake;
var food;
var score = 0;
var scoreDiv = document.getElementById('score');
var highScoreDiv = document.getElementById('highScore');
var highScore = localStorage.getItem('highScore');

//set highScore from local storage
if(!highScore) { 
  highScore = 0; 
}
highScoreDiv.innerHTML = highScore;
  
//global functions //global functions //global functions //global functions //global functions 
//////////////////////////////controls
function keyPressed() {
  switch (keyCode) {
    case 37: case 65: // left or 'a'
      snake.direction(-1,0);
      break;
    case 38: case 87: // up or 'w'
      snake.direction(0,-1);
      break;
    case 39: case 68: // right or 'd'
      snake.direction(1,0);
      break;
    case 40: case 83: // down or 's'
      snake.direction(0,1);
      break;
    default:
      break;
  }
}

//////////////////////////////collision detection
function collideWithSnake(x, y) {
  for (var i=0; i<snake.xyHistory.length; i++) {
    if(x == snake.xyHistory[i][0] && y == snake.xyHistory[i][1]) {
      return true;
    }
  }
  return false;
} 

function collideWithWall(x, y) {
  if(x<0 || y<0 || x>=dimensions || y>=dimensions) {
    return true;
  }
  return false;
}

//Snake constructor //Snake constructor //Snake constructor //Snake constructor //Snake constructor
function Snake() {
  this.x = 0-skale;
  this.y = 0;
  this.xDirection = 1;
  this.yDirection = 0;
  this.foodEaten = 0;
  this.xyHistory = [[this.x, this.y]];
  
  this.direction = function(x, y) {
    if(!collideWithSnake(this.x + skale*x, this.y + skale*y)) {
      this.xDirection = x;
      this.yDirection = y;
    }
  }

  this.show = function() {
  	fill(0,255,0);
    for(var i=0; i<this.xyHistory.length; i++) {  	 
  	   rect(this.xyHistory[i][0], this.xyHistory[i][1], skale, skale);
    }
  }

  this.update = function() {
    if(!collideWithSnake(this.x + this.xDirection*skale, this.y + this.yDirection*skale) && !collideWithWall(this.x + this.xDirection*skale, this.y + this.yDirection*skale)) {
	  	//new location
	    this.x += this.xDirection*skale;
	    this.y += this.yDirection*skale;

	    //update location history
	    this.xyHistory.push([this.x, this.y]);
	    if (this.xyHistory.length > this.foodEaten+1) {
	      this.xyHistory.shift();
	    }

	    //if eats food
	    if(this.x == food.x && this.y == food.y) {
  	      score += 100;
  	      console.log(score);
	      scoreDiv.innerHTML = score.toString();
	      this.foodEaten++;
	      food.move();
	    }
    } else {
    	if(highScore < score) {
        highScore = score;
        highScoreDiv.innerHTML = highScore;
        localStorage.setItem('highScore', highScore); 	
    	}
    	score = 0;
    	scoreDiv.innerHTML = score;
      snake = new Snake();
      food = new Food();
      food.move();
    }
  }
}

//Food constructor //Food constructor //Food constructor //Food constructor //Food constructor 
function Food() {
  this.show = function() {
    fill(255,0,255);
    rect(this.x, this.y, skale, skale);
  }
  
  this.move = function() {
    do {
      this.x = floor(random(0, dimensions/skale))*skale;
      this.y = floor(random(0, dimensions/skale))*skale;
    } while (collideWithSnake(this.x, this.y))
  }
}

//p5 setup //p5 setup //p5 setup //p5 setup //p5 setup //p5 setup //p5 setup //p5 setup 
function setup() {
  createCanvas(dimensions, dimensions);
  snake = new Snake();
  food = new Food();
  frameRate(10);
  food.move();
}

//p5 draw //p5 draw //p5 draw //p5 draw //p5 draw //p5 draw //p5 draw //p5 draw //p5 draw 
function draw() {
  background(0);
  noStroke();  
  snake.update();
  snake.show();
  food.show();
}

            
          
!
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