Snake 3.0--collision

by ElijahCirioli

HTML

<canvas width="500" height="500" id="myCanvas"></canvas>

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;
//splash screen image
var splashScreen = new Image();
splashScreen.src = "https://s15.postimg.org/suu7uk2rv/Snake_Game_Splash_Screen.jpg";
//are we playing the game?
var playing = false;
//set up tail
var tail = [];

/**
Define Game Objects here
**/
function GamePiece(x, y, size, color) {
	//assign the values
  this.x = x;
  this.y = y;
  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, 20, "red");
var food = new GamePiece(20, 20, 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.x = this.x - 20;
  }
  if(key === right) {
  	this.x = this.x + 20;
  }
  if(key === up) {
  	this.y = this.y - 20;
  }
  if(key === down) {
  	this.y = this.y + 20;
  }
}

//check to see if the head is touching anything
head.hitTest = function(ob) {
	//ask the question: is it touching ob?
  if(this.x === ob.x && this.y === ob.y) {
  	return true;
  }
  //default is not true
  return false;
}

//define how food moves
food.move = function() {
	//define new x value
  var newx = Math.random() * 25;
  //round it down
  newx = Math.floor(newx);
  //multiply by 20
  newx = newx * 20; 
  var newy = Math.random() * 25;
  //round it down
  newy = Math.floor(newy);
  //multiply by 20
  newy = newy * 20;
  //reassign the values
  this.x = newx;
  this.y = newy;
}

/**
drawing the game and performing logic
**/
function draw() {
   ...