//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() {
...
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.