Snake Game

jQuery Snake game

by Andrejs Gubars

HTML

<canvas id="canvas" width="450" height="450"></canvas>
<div id="result"></div>

JavaScript

$(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>' +...