var Base = Base || {};
Base.Snake = function() {
// Create the Canvas Object tell it 2d
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
settings = {
speed: 60,
blockSize: 10
},
opt = settings,
snake_array,
direction,
food,
score,
registered = false,
player,
PHPplayer;
function init() {
direction = 'right';
score = 0;
opt.speed = 60;
create_snake();
create_food();
getHighScore();
// game_loop is == a number/object when it kicks in
// then we clearInterval, if not we start fresh
if (typeof game_loop != "undefined") {
clearInterval(game_loop);
}
game_loop = setInterval(paint, opt.speed);
}
function paintCanvas() {
ctx.fillStyle = 'yellow';
ctx.fillRect(0, 0, w, h);
}
function create_snake() {
var length = 5;
snake_array = []
for (i = length - 1; i >= 0; i--) {
snake_array.push({
x: i,
y: 0
});
}
}
function create_food() {
food = {
x: Math.round(Math.random() * (w - opt.blockSize) / opt.blockSize),
y: Math.round(Math.random() * (h - opt.blockSize) / opt.blockSize),
};
if (check_collision(food.x, food.y, snake_array)) {
create_food();
}
}
function paint() {
paintCanvas()
var nx = snake_array[0].x;
var ny = snake_array[0].y;
if (direction == "right") {
nx++;
} else if (direction == "left") {
nx--;
}
// If we're going up then we're subtracting from the y axis
else if (direction == "up") {
ny--;
}
// If we're going down then we're adding to the y axis
else if (direction == "down") {
ny++;
}
if (nx == -1 || nx == w / opt.blockSize || ny == -1 || ny == h / opt.blockSize ||
check_collision(nx, ny, snake_array)) {
submitInfo(score);
// Call the init and...
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.