Snakes Game

This is a small demo of the snakes game. This is made in order to learn the basics of gaming by making a complete snakes game.

by shivkumarganesh

JavaScript

var JS_SNAKE = {};

JS_SNAKE.game = (function () {
  var ctx;
  var xPosition = 0;
  var yPosition = 0;
  var frameLength = 500; //new frame every 0.5 seconds

  function init() {
    $('body').append('<canvas id="jsSnake">');
    var $canvas = $('#jsSnake');
    $canvas.attr('width', 100);
    $canvas.attr('height', 100);
    var canvas = $canvas[0];
    ctx = canvas.getContext('2d');
    gameLoop();
  }

  function gameLoop() {
    xPosition += 2;
    yPosition += 4;
    ctx.clearRect(0, 0, 100, 100); //clear the canvas
    ctx.fillStyle = '#fe57a1';
    ctx.fillRect(xPosition, yPosition, 30, 50); //a moving rect
    setTimeout(gameLoop, frameLength); //do it all again
  }

  return {
    init: init
  };
})();


$(document).ready(function () {
  JS_SNAKE.game.init();
});