$(document).ready(function() {
//Canvas stuff
var global_score = 0;
var top_scores = [];
var lives = 3;
var keys = [];
var interval;
$('body').on('click', '#play', function() {
lives = 3;
inverval = "";
top_scores = [];
global_score = 0;
$('#play').remove();
$('#result').html('');
init();
});
window.addEventListener("keydown",
function(e) {
keys[e.keyCode] = true;
switch (e.keyCode) {
case 37:
case 39:
case 38:
case 40: // Arrow keys
case 32:
e.preventDefault();
break; // Space
default:
break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e) {
keys[e.keyCode] = false;
},
false);
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
//Lets save the cell width in a variable for easy control
var cw = 10;
var d;
var food;
var score;
//Lets create the snake now
var snake_array; //an array of cells to make up the snake
function init() {
d = "right"; //default direction
create_snake();
create_food(); //Now we can see the food particle
//finally lets display the score
score = 0;
//Lets move the snake now using a timer which will trigger the paint function
//every 60ms
if (lives > 0) {
if (typeof game_loop != "undefined") {
clearInterval(game_loop);
game_loop = setInterval(paint, 60);
} else if (interval === null) {
return false;
} else {
game_loop = setInterval(paint, 60);
}
} else {
clearInterval(game_loop);
var li = '';
for (var i = 0; i < top_scores.length; i++) {
li += '<li> Score for round ' + (i + 1) + " is: " + top_scores[i] + ' points</li>';
}
$('#result').html('<ul>' + li + '</ul><hr><p> Best Score is: <strong><u>' +...
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.