//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 ||...
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.