Snake

A snake game I made...

by Tsskyx

HTML

<!--this is a link to the p5.js library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.6/p5.min.js"></script>

JavaScript

var gridsize = 21;
var FPS = 6;

function Body(pos) {
  this.pos = createVector(pos.x, pos.y);
  this.rect1 = createVector(cellsize / 2 + 2 * cellsize * this.pos.x, cellsize / 2 + 2 * cellsize * this.pos.y);
  this.rect2 = createVector(this.rect1.x - cellsize * nextpos.x, this.rect1.y - cellsize * nextpos.y);

  this.display = function() {
    rect(this.rect1.x, this.rect1.y, cellsize + 1, cellsize + 1);
    if (snake[0] != this) {
      rect(this.rect2.x, this.rect2.y, cellsize + 1, cellsize + 1);
    }
  }
}

function Food(index) {
  this.pos = createVector(emptycells[index].x, emptycells[index].y);

  this.display = function() {
    this.fpos = createVector(cellsize / 2 + 2 * cellsize * this.pos.x, cellsize / 2 + 2 * cellsize * this.pos.y);
    ellipse(this.fpos.x, this.fpos.y, cellsize, cellsize);
  }
}

var gamemode = 0, cellsize, emptycells, snake, headpos, nextpos, foodindex, food, direction, keylock, showhint = true, endlock;
var grid = new Array(gridsize);

function setup() {
  createCanvas(600, 600);
  cellsize = width / gridsize / 2;
  headpos = createVector(0, 0);
  nextpos = createVector(0, 0);
  for (var i = 0; i < grid.length; i++) {
    grid[i] = new Array(gridsize);
  }
  resetFormat();
}

function resetFormat() {
  ellipseMode(CORNER);
  rectMode(CORNER);
  textAlign(CENTER, CENTER);
  textSize(30);
  fill(255);
  noStroke();
}

function draw() {
  switch (gamemode) {
    case 0:
      menu();
      break;
    case 1:
      load();
      break;
    case 2:
      play();
      break;
    case 3:
      end();
  }
  endlock = keyIsPressed && key == " " ? true : false;
}

function keyPressed() {
  if (gamemode == 1 && keyCode > 36 && keyCode < 41) {
    gamemode = 2;
    loop();
  }

  if (gamemode == 2 && !keylock) {
    keylock = true;

    if (keyCode == 37 && direction != 2) {
      nextpos.set(-1, 0);
      direction = 0;
    }

    if (keyCode == 38 && direction != 3) {
      nextpos.set(0, -1);
      direction = 1;
    }

    if (keyCode ==...