Eli Snake

by ElijahCirioli

HTML

<canvas width="700" height="500" id="myCanvas"></canvas>
<audio src = "https://docs.google.com/uc?export=download&id=0B9uzykIixHuYVjB3ZW9BcnBVNWs" autoplay loop>
</audio>

CSS

#myCanvas {
    border 0px solid #000;
}

JavaScript

//canvas values
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

//key codes for key controls
var left = 37;//left arrow
var right = 39;//right arrow
var up = 38;//up arrow
var down = 40;//down arrow
var key = 0;
var highScore = 0;
var dif = 2;
//splash screen image
var splashScreen = new Image();
var keyControls = new Image();
splashScreen.src = "https://s9.postimg.org/cc8q916y7/Snake_Splash.png";
keyControls.src = "https://s9.postimg.org/fot2w5m9r/KC8.png";
//are we playing the game?
var playing = false;
//set up tail
var tail = [];

/**
Define Game Objects here
**/
function GamePiece(x, y, xspeed, yspeed, size, color) {
	//assign the values
  this.x = x;
  this.y = y;
  this.xspeed = xspeed;
  this.yspeed = yspeed;
  this.size = size;
  this.color = color;
}

//draw the game piece
GamePiece.prototype.draw = function() {
	//assign a color
  context.fillStyle = this.color;
  //draw a rectangle
  context.fillRect(this.x, this.y, this.size, this.size);
}

//moment of truth--can I make game pieces??????
var head = new GamePiece(240, 240, 0, 0, 20, "red");
var food = new GamePiece(240, 240, 0, 0, 20, "limeGreen");

//this is what I do: I tell the head how to move
head.move = function() {
	//evaluate key presses for certain important values
  if(key === left && (this.xspeed === 0 || tail.length < 2)) {
	this.xspeed = -20;
  this.yspeed = 0;
  }
  if(key === right && (this.xspeed === 0 || tail.length < 2)) {
	this.xspeed = 20;
  this.yspeed = 0;
  }
  if(key === up && (this.yspeed === 0 || tail.length < 2)) {
	this.yspeed = -20;
  this.xspeed = 0;
  }
  if(key === down && (this.yspeed === 0 || tail.length < 2)) {
	this.yspeed = 20;
  this.xspeed = 0;
  }
  this.x = this.x + this.xspeed;
  this.y = this.y + this.yspeed;
  
  if (this.x < 0 || this.x + 20 > 500 || this.y < 0 || this.y + 20 > 500) {
  	this.death();
  }
}

//check to see if the head is touching anything
head.hitTest = function(ob) {
	//ask the question: is it...