Snake 1.0

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
//variable to keep track of key pressed
var key = 0;

//splash screen image
var splashScreen = new Image();
splashScreen.src = "https://s12.postimg.org/ia2a1eza5/Snake_Game_Splash_Screen.jpg";
var playing = false;

/*
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 game pieces
GamePiece.prototype.draw = function() {
	//assign a color
	context.fillStyle = this.color;
	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(60, 60, 20, "limeGreen");
//teaching the head to move
head.move = function() {
	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;
  }
}

/*
drawing the game and performing logic
*/
function draw() {
    //background
    context.fillStyle = "black";
    context.fillRect(0, 0, 500, 500);
    
    //if we're not playing
    if (playing === false) {
    //splash screen
    context.drawImage(splashScreen, 0, 0, 500, 500);
    context.fillStyle = "darkRed";
    context.font = "30px arial"
    context.fillText("Press Any Key To Start", 105, 450)
    }
    
    //if we're playing
    if (playing === true) {
    head.draw();
    food.draw();
    head.move();
    }
}

/*
Game management section
*/
//frame rate
var framerate = 1000/10;
//call the interval for animation and drawing
var thread = setInterval(draw, framerate);

/**
key controls to capture key events
**/
document.onkeydown = function (e) {
    //capture the event
    e = window.event ||...