//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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.