<commit_before>(function bouncer() {
  "use strict";

  var Game = window.Game;

  var $ = document.getElementById.bind(document);
  var screen = $("screen");
  var eltMessage = $("message");
  var width = window.innerWidth;
  var height = window.innerHeight;
  var eltScore = $("score");
  var eltMultiplier = $("multiplier");
  var eltHealth = $("health");

  /**
   * The time at which some events happened, in milliseconds since the epoch.
   */
  var timeStamps = {
    /**
     * The start of the game
     */
    gameStart: Date.now(),

    /**
     * Instant at which the previous frame started being prepared
     */
    previousFrame: Date.now() - 15,

    /**
     * Instant at which the current frame started being prepared
     */
    currentFrame: Date.now(),

    /**
     * Instant at which we launched the latest ball
     */
    latestBallLaunch: 0,

    /**
     * Instant at the lastest score multiplier update
     */
    lastestMultiplierUpdate: Date.now(),
 };

  /**
   * The different scores and the multiplier of the current game
   */
  var score = {
    /**
     * The score of the older frame
     */
    previous: -1,

    /**
     * The score in the current frame
     */
    current: 0,

    /**
     * The score multiplier, increase when the game lasts longer
     */
    multiplier: 1,
  };

  /**
   * The different values for health in current game
   */
  var health = {
    /**
     * The health of the older frame
     */
    previous: 0,

    /**
     * The health in the current frame
     */
    current: Game.Config.Health.defaultStarting,
  };

  var Sprite = Game.Sprite;
  var Ball = Game.Ball;

  // Shortcut: an array with all the pads
  var pads = [];

  // Initialize sprites
  var padNorth = new Sprite("pad_north");
  var padSouth = new Sprite("pad_south");
  var padEast = new Sprite("pad_east");
  var padWest = new Sprite("pad_west");

  padNorth.setPosition("center", "top");
  padSouth.setPosition("center", "bottom");
  padEast.setPosition("left", "center");
  padWest.setPosition("right", "center");
  for (var pad of [padNorth, padSouth, padEast, padWest]) {
    pads.push(pad);
    Sprite.all.add(pad);
  }

  Sprite.all.forEach(function (sprite) {
    sprite.writeToDOM();
  });

  // Handle events

  function onmove(e) {
    for (var pad of pads) {
      pad.event.pageX = e.pageX;
      pad.event.pageY = e.pageY;
    }
    e.stopPropagation();
    e.preventDefault();
  }
  function ontouch(e) {
    onmove(e);
    Pause.resume();
  }
  window.addEventListener("mousemove", onmove);
  window.addEventListener("mouseup", ontouch);
  window.addEventListener("touchstart", ontouch);
  window.addEventListener("touchmove", ontouch);

  /**
   * An object centralizing pause information.
   */
  var Pause = Game.Pause = {
    /**
     * true if the game is on pause, false otherwise
     */
    isPaused: false,

    /**
     * Put the game on pause.
     *
     * Has no effect if the game is already on pause.
     */
    start: function() {
      Pause.isPaused = true;
      eltMessage.classList.add("visible");
      eltMessage.textContent = "Pause";
    },

    /**
     * Resume the game.
     *
     * Has no effect if the game is not on pause.
     */
    resume: function() {
      if (!Pause.isPaused) {
        return;
      }
      Pause.isPaused = false;
      eltMessage.classList.remove("visible");

      // Make sure that the game doesn't freak out by launching balls,
      // increasing speed, etc.
      var now = Date.now();
      timeStamps.previousFrame = now - 15;
      timeStamps.currentFrame = now;
      timeStamps.latestBallLaunch = now;

      // Resume game
      requestAnimationFrame(loop);
    },

    /**
     * Switch between on pause/out of pause.
     */
    revert: function() {
      if (Pause.isPaused) {
        Pause.resume();
      } else {
        Pause.start();
      }
    }
  };
  window.addEventListener("keydown", function(event) {
    var code = event.keyCode || event.which || null;
    if (code == null) {
      // No code information, this must be an old version of
      // Internet Explorer
      return;
    }
    if (code != window.KeyEvent.DOM_VK_SPACE) {
      // Not the space key
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    Pause.revert();
  });
  window.addEventListener("blur", function() {
    Pause.start();
  });

  var nextFrame = function() {

    // -------- Read from DOM -------------

    // All reads from DOM *must* happen before the writes to DOM.
    // Otherwise, we end up recomputing the layout several times
    // for a frame, which is very much not good.

    Sprite.all.forEach(function (sprite) {
      sprite.readFromDOM();
    });

    Ball.flushPending(pads);

    Sprite.width = width = window.innerWidth;
    Sprite.height = height = window.innerHeight;

    // --------- Done reading from DOM ----

    var deltaT = timeStamps.currentFrame - timeStamps.previousFrame;

    // Return pause
    if (Pause.isPaused) {
      return false;
    }

    // Handle ball bouncing
    for (var ball of Ball.balls) {

      if (ball.event.dx < 0) {
        ball.bounceX.check(ball.x <= 0, "E", padEast);
      } else if (ball.event.dx > 0) {
        ball.bounceX.check(ball.E >= width, "W", padWest);
      }

      if (ball.event.dy < 0) {
        ball.bounceY.check(ball.y <= 0, "S", padSouth);
      } else if (ball.event.dy > 0) {
        ball.bounceY.check(ball.S >= height, "N", padNorth);
      }

      var collisionWithWall = ball.bounceX.bounceOnWall ||
        ball.bounceY.bounceOnWall;

      var collisionWithPad = !collisionWithWall &&
        ball.bounceX.bounceOnPad ||
        ball.bounceY.bounceOnPad;

      ball.updateVector();

      // Update the current score and current health
      if (collisionWithPad) {
        if (timeStamps.currentFrame - timeStamps.lastestMultiplierUpdate >= 10000) {
          score.multiplier += 0.5;
          timeStamps.lastestMultiplierUpdate = timeStamps.currentFrame;
        }
        score.current += Game.Config.Score.bounceOnPad * score.multiplier;
        health.current += Game.Config.Health.regenerate;
      } else if (collisionWithWall) {
        score.current += Game.Config.Score.bounceOnWall;
        health.current += Game.Config.Health.hurt;
      }
    }

    // Update position of sprites
    // Note that we set both x and y, even for sprites that can move only
    // laterally/vertically, to ensure that we keep the game flowing even
    // in case of screen resize or orientation change.
    padNorth.nextX = padNorth.event.pageX - padNorth.width / 2;
    padNorth.nextX = Game.Utils.restrictToSegment(padNorth.nextX, 0, width - padNorth.width);
    padNorth.ypos = "top";

    padSouth.nextX = padSouth.event.pageX - padSouth.width / 2;
    padSouth.nextX = Game.Utils.restrictToSegment(padSouth.nextX, 0, width - padSouth.width);
    padSouth.ypos = "bottom";

    padEast.nextY = padEast.event.pageY - padEast.height / 2;
    padEast.nextY = Game.Utils.restrictToSegment(padEast.nextY, 0, height - padEast.height);
    padEast.xpos = "right";

    padWest.nextY = padWest.event.pageY - padWest.height / 2;
    padWest.nextY = Game.Utils.restrictToSegment(padWest.nextY, 0, height - padWest.height);
    padWest.xpos = "left";

    for (ball of Ball.balls) {
      ball.nextX = ball.x + Math.round(ball.event.dx * ball.event.speed * deltaT);
      ball.nextY = ball.y + Math.round(ball.event.dy * ball.event.speed * deltaT);
    }

    // FIXME: Handle health, win/lose

    // FIXME: Handle game speed

    // FIXME: Handle score

    // -------- Write to DOM -------------

    // Prepare new balls
    if (timeStamps.currentFrame - timeStamps.latestBallLaunch >=
      Game.Config.intervalBetweenBalls) {
      Ball.prepare(screen);
      timeStamps.latestBallLaunch = timeStamps.currentFrame;
    }

    // Update ball colors
    for (ball of Ball.balls) {
      if (ball.bounceX.bounceOnPad || ball.bounceY.bounceOnPad) {
        ball.changeBallColor();
      }
    }
    Sprite.all.forEach(function (sprite) {
      sprite.writeToDOM();
    });
    screen.style.width = width;
    screen.style.height = height;

    // Update the score if it has changed
    if (score.current != score.previous) {
      eltScore.textContent = score.current + " pts";
      score.previous = score.current;
    }

    // Update the score multiplier if it has changed
    if (timeStamps.lastestMultiplierUpdate == timeStamps.currentFrame && score.multiplier > 1) {
      eltMultiplier.textContent = "x " + score.multiplier;
    }

    // Update the health if it has changed
    if (health.current != health.previous) {
      eltHealth.textContent = health.current + " ❤";
      health.previous = health.current;
    }

    // -------- Write to DOM -------------

    return true;
  };

  nextFrame();

  // Main loop
  function loop() {
    timeStamps.previousFrame = timeStamps.currentFrame;
    timeStamps.currentFrame = Date.now();

    if (health.current <= 0) {
      eltHealth.textContent = 0 + " ❤";

      if (score.current > 0) {
        eltMessage.textContent = 'Congratulations, you have ' + score.current + " points !";
        eltMessage.classList.add("visible");
      } else {
        eltMessage.textContent = 'You lose :-(';
        eltMessage.classList.add("visible");
      }
    } else {
      nextFrame();
      requestAnimationFrame(loop);
    }
  };
  requestAnimationFrame(loop);
})();

<commit_msg>Issue #56: change for..of to for..in<commit_after>(function bouncer() {
  "use strict";

  var Game = window.Game;

  var $ = document.getElementById.bind(document);
  var screen = $("screen");
  var eltMessage = $("message");
  var width = window.innerWidth;
  var height = window.innerHeight;
  var eltScore = $("score");
  var eltMultiplier = $("multiplier");
  var eltHealth = $("health");

  /**
   * The time at which some events happened, in milliseconds since the epoch.
   */
  var timeStamps = {
    /**
     * The start of the game
     */
    gameStart: Date.now(),

    /**
     * Instant at which the previous frame started being prepared
     */
    previousFrame: Date.now() - 15,

    /**
     * Instant at which the current frame started being prepared
     */
    currentFrame: Date.now(),

    /**
     * Instant at which we launched the latest ball
     */
    latestBallLaunch: 0,

    /**
     * Instant at the lastest score multiplier update
     */
    lastestMultiplierUpdate: Date.now(),
 };

  /**
   * The different scores and the multiplier of the current game
   */
  var score = {
    /**
     * The score of the older frame
     */
    previous: -1,

    /**
     * The score in the current frame
     */
    current: 0,

    /**
     * The score multiplier, increase when the game lasts longer
     */
    multiplier: 1,
  };

  /**
   * The different values for health in current game
   */
  var health = {
    /**
     * The health of the older frame
     */
    previous: 0,

    /**
     * The health in the current frame
     */
    current: Game.Config.Health.defaultStarting,
  };

  var Sprite = Game.Sprite;
  var Ball = Game.Ball;

  // Shortcut: an array with all the pads
  var pads = [];

  // Initialize sprites
  var padNorth = new Sprite("pad_north");
  var padSouth = new Sprite("pad_south");
  var padEast = new Sprite("pad_east");
  var padWest = new Sprite("pad_west");

  padNorth.setPosition("center", "top");
  padSouth.setPosition("center", "bottom");
  padEast.setPosition("left", "center");
  padWest.setPosition("right", "center");

  pads = [padNorth, padSouth, padEast, padWest];
  for (var index in pads) {
    Sprite.all.add(pads[index]);
  }

  Sprite.all.forEach(function (sprite) {
    sprite.writeToDOM();
  });

  // Handle events

  function onmove(e) {
    for (var index in pads) {
      pads[index].event.pageX = e.pageX;
      pads[index].event.pageY = e.pageY;
    }
    e.stopPropagation();
    e.preventDefault();
  }
  function ontouch(e) {
    onmove(e);
    Pause.resume();
  }
  window.addEventListener("mousemove", onmove);
  window.addEventListener("mouseup", ontouch);
  window.addEventListener("touchstart", ontouch);
  window.addEventListener("touchmove", ontouch);

  /**
   * An object centralizing pause information.
   */
  var Pause = Game.Pause = {
    /**
     * true if the game is on pause, false otherwise
     */
    isPaused: false,

    /**
     * Put the game on pause.
     *
     * Has no effect if the game is already on pause.
     */
    start: function() {
      Pause.isPaused = true;
      eltMessage.classList.add("visible");
      eltMessage.textContent = "Pause";
    },

    /**
     * Resume the game.
     *
     * Has no effect if the game is not on pause.
     */
    resume: function() {
      if (!Pause.isPaused) {
        return;
      }
      Pause.isPaused = false;
      eltMessage.classList.remove("visible");

      // Make sure that the game doesn't freak out by launching balls,
      // increasing speed, etc.
      var now = Date.now();
      timeStamps.previousFrame = now - 15;
      timeStamps.currentFrame = now;
      timeStamps.latestBallLaunch = now;

      // Resume game
      requestAnimationFrame(loop);
    },

    /**
     * Switch between on pause/out of pause.
     */
    revert: function() {
      if (Pause.isPaused) {
        Pause.resume();
      } else {
        Pause.start();
      }
    }
  };
  window.addEventListener("keydown", function(event) {
    var code = event.keyCode || event.which || null;
    if (code == null) {
      // No code information, this must be an old version of
      // Internet Explorer
      return;
    }
    if (code != window.KeyEvent.DOM_VK_SPACE) {
      // Not the space key
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    Pause.revert();
  });
  window.addEventListener("blur", function() {
    Pause.start();
  });

  var nextFrame = function() {

    // -------- Read from DOM -------------

    // All reads from DOM *must* happen before the writes to DOM.
    // Otherwise, we end up recomputing the layout several times
    // for a frame, which is very much not good.

    Sprite.all.forEach(function (sprite) {
      sprite.readFromDOM();
    });

    Ball.flushPending(pads);

    Sprite.width = width = window.innerWidth;
    Sprite.height = height = window.innerHeight;

    // --------- Done reading from DOM ----

    var deltaT = timeStamps.currentFrame - timeStamps.previousFrame;

    // Return pause
    if (Pause.isPaused) {
      return false;
    }

    // Handle ball bouncing
    for (var index in Ball.balls) {
      var ball = Ball.balls[index];

      if (ball.event.dx < 0) {
        ball.bounceX.check(ball.x <= 0, "E", padEast);
      } else if (ball.event.dx > 0) {
        ball.bounceX.check(ball.E >= width, "W", padWest);
      }

      if (ball.event.dy < 0) {
        ball.bounceY.check(ball.y <= 0, "S", padSouth);
      } else if (ball.event.dy > 0) {
        ball.bounceY.check(ball.S >= height, "N", padNorth);
      }

      var collisionWithWall = ball.bounceX.bounceOnWall ||
        ball.bounceY.bounceOnWall;

      var collisionWithPad = !collisionWithWall &&
        ball.bounceX.bounceOnPad ||
        ball.bounceY.bounceOnPad;

      ball.updateVector();

      // Update the current score and current health
      if (collisionWithPad) {
        if (timeStamps.currentFrame - timeStamps.lastestMultiplierUpdate >= 10000) {
          score.multiplier += 0.5;
          timeStamps.lastestMultiplierUpdate = timeStamps.currentFrame;
        }
        score.current += Game.Config.Score.bounceOnPad * score.multiplier;
        health.current += Game.Config.Health.regenerate;
      } else if (collisionWithWall) {
        score.current += Game.Config.Score.bounceOnWall;
        health.current += Game.Config.Health.hurt;
      }
    }

    // Update position of sprites
    // Note that we set both x and y, even for sprites that can move only
    // laterally/vertically, to ensure that we keep the game flowing even
    // in case of screen resize or orientation change.
    padNorth.nextX = padNorth.event.pageX - padNorth.width / 2;
    padNorth.nextX = Game.Utils.restrictToSegment(padNorth.nextX, 0, width - padNorth.width);
    padNorth.ypos = "top";

    padSouth.nextX = padSouth.event.pageX - padSouth.width / 2;
    padSouth.nextX = Game.Utils.restrictToSegment(padSouth.nextX, 0, width - padSouth.width);
    padSouth.ypos = "bottom";

    padEast.nextY = padEast.event.pageY - padEast.height / 2;
    padEast.nextY = Game.Utils.restrictToSegment(padEast.nextY, 0, height - padEast.height);
    padEast.xpos = "right";

    padWest.nextY = padWest.event.pageY - padWest.height / 2;
    padWest.nextY = Game.Utils.restrictToSegment(padWest.nextY, 0, height - padWest.height);
    padWest.xpos = "left";

    for (var index in Ball.balls) {
      var ball = Ball.balls[index];
      ball.nextX = ball.x + Math.round(ball.event.dx * ball.event.speed * deltaT);
      ball.nextY = ball.y + Math.round(ball.event.dy * ball.event.speed * deltaT);
    }

    // FIXME: Handle health, win/lose

    // FIXME: Handle game speed

    // FIXME: Handle score

    // -------- Write to DOM -------------

    // Prepare new balls
    if (timeStamps.currentFrame - timeStamps.latestBallLaunch >=
      Game.Config.intervalBetweenBalls) {
      Ball.prepare(screen);
      timeStamps.latestBallLaunch = timeStamps.currentFrame;
    }

    // Update ball colors
    for (var index in Ball.balls) {
      var ball = Ball.balls[index];
      if (ball.bounceX.bounceOnPad || ball.bounceY.bounceOnPad) {
        ball.changeBallColor();
      }
    }
    Sprite.all.forEach(function (sprite) {
      sprite.writeToDOM();
    });
    screen.style.width = width;
    screen.style.height = height;

    // Update the score if it has changed
    if (score.current != score.previous) {
      eltScore.textContent = score.current + " pts";
      score.previous = score.current;
    }

    // Update the score multiplier if it has changed
    if (timeStamps.lastestMultiplierUpdate == timeStamps.currentFrame && score.multiplier > 1) {
      eltMultiplier.textContent = "x " + score.multiplier;
    }

    // Update the health if it has changed
    if (health.current != health.previous) {
      eltHealth.textContent = health.current + " ❤";
      health.previous = health.current;
    }

    // -------- Write to DOM -------------

    return true;
  };

  nextFrame();

  // Main loop
  function loop() {
    timeStamps.previousFrame = timeStamps.currentFrame;
    timeStamps.currentFrame = Date.now();

    if (health.current <= 0) {
      eltHealth.textContent = 0 + " ❤";

      if (score.current > 0) {
        eltMessage.textContent = 'Congratulations, you have ' + score.current + " points !";
        eltMessage.classList.add("visible");
      } else {
        eltMessage.textContent = 'You lose :-(';
        eltMessage.classList.add("visible");
      }
    } else {
      nextFrame();
      requestAnimationFrame(loop);
    }
  };
  requestAnimationFrame(loop);
})();

<|endoftext|>


<commit_before>(function() {
  var asciiContainer = document.getElementById("video");
  var capturing = false;
  var patch;
  var differ = new diff_match_patch();
  differ.Diff_Timeout = 1/30;

  camera.init({
    width: 160,
    height: 120,
    fps: 30,
    mirror: true,

    onFrame: function(canvas) {
      ascii.fromCanvas(canvas, {
        callback: function(asciiString) {
          //asciiContainer.innerHTML = asciiString;
          patch = differ.patch_make(asciiContainer.innerHTML, asciiString);
          //console.log(patch);
          var newAscii = differ.patch_apply(patch, asciiContainer.innerHTML)[0];
          //console.log(newAscii);
          asciiContainer.innerHTML = newAscii;
        }
      });
    },

    onSuccess: function() {
      capturing = true;
      asciiContainer.style.display = "block";
    },

    onNotSupported: function() {
      document.getElementById("info").style.display = "none";
      asciiContainer.style.display = "none";
      document.getElementById("notSupported").style.display = "block";
    }
  });
})();
<commit_msg>Removed logging<commit_after>(function() {
  var asciiContainer = document.getElementById("video");
  var capturing = false;
  var patch;
  var differ = new diff_match_patch();
  differ.Diff_Timeout = 1/30;

  camera.init({
    width: 160,
    height: 120,
    fps: 30,
    mirror: true,

    onFrame: function(canvas) {
      ascii.fromCanvas(canvas, {
        callback: function(asciiString) {
          patch = differ.patch_make(asciiContainer.innerHTML, asciiString);
          var newAscii = differ.patch_apply(patch, asciiContainer.innerHTML)[0];
          asciiContainer.innerHTML = newAscii;
        }
      });
    },

    onSuccess: function() {
      capturing = true;
      asciiContainer.style.display = "block";
    },

    onNotSupported: function() {
      document.getElementById("info").style.display = "none";
      asciiContainer.style.display = "none";
      document.getElementById("notSupported").style.display = "block";
    }
  });
})();
<|endoftext|>


<commit_before>var boxes = [ 2, 2,
			  3, 3,
			  4, 4,
			  5, 5, 5,
			  6, 6, 6, 6, 6,
			  7, 7, 7, 7, 7, 7, 7,
			  8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
			  9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
		      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
		      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
		      11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      ];

var colrs = ["#b71c1c", "#006064", "#C51162", "#F50057", "#6A1B9A",
  "#880E4F", "#673AB7", "#303F9F", "#0D47A1", "#607D8B", "#2E7D32",
  "#00695C", "#01579B", "#FF6F00", "#424242", "#FF5722", "#BF360C",
  "#795548", "#E65100", "#6200EA", "#9C27B0", "#9E9D24", "#263238",
  "#d50000", "#0D47A1", "#4A148C", "#3E2723", "#00695C", "#827717",

  			 "#b71c1c", "#006064", "#C51162", "#F50057", "#6A1B9A",
  "#880E4F", "#673AB7", "#303F9F", "#0D47A1", "#607D8B", "#2E7D32",
  "#00695C", "#01579B", "#FF6F00", "#424242", "#FF5722", "#BF360C",
  "#795548", "#E65100", "#6200EA", "#9C27B0", "#9E9D24", "#263238",
  "#d50000", "#0D47A1", "#4A148C", "#3E2723", "#00695C", "#827717"];

var score = 0;
var seconds;
var temp;
var randomBox;
var col;
var opacy = 0.77;

var factorial = function (number){
	if (number ===0 || number === 1)
		return 1;
	return factorial(number-1)*number;
};

var index = 0;
var help = false;

var bigbox = document.getElementById("bigbox");
var boxH = getComputedStyle(bigbox).getPropertyValue("height");

var max_size = factorial(Math.max(...boxes));
var bigBoxSize = boxH.slice(0,boxH.length - 2);

function createSmallBox(total_extra_space, no_of_box){

	var h = bigBoxSize - total_extra_space;

	console.log(h);

	h = h/no_of_box + "px";

	var SmallBox = document.createElement("div");

	SmallBox.id = "SmallBox";
	SmallBox.style.backgroundColor = col;
	SmallBox.style.height = h;
	SmallBox.style.width = h;
	bigbox.appendChild(SmallBox);
}

function scoreUpdater () {
	 ScoreDiv = document.getElementById("score");
	 ScoreDiv.innerHTML = "Score: " + score;
}

function randomBoxSelector() {
	 var allChilds = bigbox.childNodes;
	 randomBox = allChilds[Math.floor((Math.random() * (boxes[index]*boxes[index])))];
	 randomBox.style.opacity = opacy;

	 if(index % 2 == 0)
		{
			opacy = opacy + 0.004;
		}

		 randomBox.onclick = function (){
	 	 if(index == 1){
	 	 	document.getElementById('countdown').innerHTML = 60 + 1;
	 	 	 //Set the time here.
	 	 	countdown();
	 	 }
	 	 score++;
	 	 scoreUpdater();
	 	 start();
	 }
}

function create(){
	col = colrs[Math.floor((Math.random() * (colrs.length)))];
	for(var i=0; i<boxes[index]*boxes[index]; i++){
		var extra_spaces = 6 * boxes[index];
		createSmallBox(extra_spaces, boxes[index]);
	}
	randomBoxSelector();
}

function scoreplay () {
	 bigbox.style.backgroundColor = "black";
	 bigbox.style.fontSize = bigBoxSize * 0.13 + "px";
	 bigbox.style.color = "white";
	 bigbox.style.textAlign = "center";
	 bigbox.style.fontFamily = "'Passion One', cursive, sans-serif";

	 bigbox.innerHTML = "

Your Score: " + score;

	 bigbox.innerHTML = bigbox.innerHTML + "

 Tap to Replay";

	 bigbox.onclick = function () {
	 	 location.reload();
	 }

}

function countdown() {
	seconds = document.getElementById('countdown').innerHTML;
	seconds = parseInt(seconds, 10);

	if (seconds == 1) {
		temp = document.getElementById('countdown');
		temp.innerHTML = "Game Over";
		randomBox.style.backgroundColor = "black";
		randomBox.onclick = null;
		scoreplay();
		// window.alert("Your Score = " + score);
		}

	seconds--;
        if (seconds === 0){
            var game_over = document.getElementById("game_over");
            game_over.play();
        }
        else{
	    var tick = document.getElementById('tick');
	    tick.volume = Math.max((60 - seconds) / 60, 0.5);
	    tick.play();
        }
	temp = document.getElementById('countdown');
	temp.innerHTML = seconds;
	timeoutMyOswego = setTimeout(countdown, 1000);
}

function start(){
	if(index >= boxes.length)
		window.alert("Either you found a hack or you are GOD. Your Score = " + score);
		//This won't happen. let the player have no limits
	else{
		var bigBox = document.getElementById('bigbox');
		while(bigBox.firstChild){
			bigBox.removeChild(bigBox.firstChild);
		}
		create();
		index++;
	}
}

window.onload = function () {
	start();
};

window.onresize = function () {
	location.reload();
};

var populate_help = function () {
	var help_obj = document.getElementById("help");
	var help_obj_div = document.createElement('div');
	help_obj_div.id = "help-text";

	help_obj_text = "
Society is always hard on the odd ones and so is this game. Seperate as many odd boxes from the matrix as you can while the Timer is still ticking.
"+
					"
Try to differentiate as fast as you can to check your reflexes and sense of judgement.
" +
					"
By: htadg
";

	help_obj_div.innerHTML += help_obj_text;

	help_obj.appendChild(help_obj_div);
};

var help_height = $("#help").height();
var help_width = $("#help").width();

$("#help").click(function () {
	if (!help){
		$("#help").animate({
			height: "240px",
			width: "300px"
		}, 500);
		populate_help();
		help = true;
	}
	else{
		$("#help-text").remove();
		$('#help').animate({
			height: ""+help_height+"px",
			width: ""+help_width+"px"
		}, 500);
		help = false;
	}
});

var leaderboard;

function createCORSRequest (method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else{
        xhr = null;
    }
    return xhr;
}

function getLeaderBoard () {
    var url = "http://kube-server.herokuapp.com/score/api/v1/get";
    var xhr = createCORSRequest('GET', url);
    if (!xhr){
        alert('CORS not supported');
        return;
    }
    xhr.onload = function () {
        console.log(xhr.responseText);
        leaderboard = xhr.responseText;
        alert('Response from CORS request to ' + url);
    };
    xhr.onerror = function () {
        alert('Woops, there was an error making the request.');
    };
    xhr.withCredentials = true;
    xhr.send();
}

$("#leaderboard").click(function () {
    var leaderboard = leaderboard || getLeaderBoard();
    console.log(leaderboard);
});

<commit_msg>nothing to worry<commit_after>var boxes = [ 2, 2,
			  3, 3,
			  4, 4,
			  5, 5, 5,
			  6, 6, 6, 6, 6,
			  7, 7, 7, 7, 7, 7, 7,
			  8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
			  9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
		      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
		      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
		      11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
		      ];

var colrs = ["#b71c1c", "#006064", "#C51162", "#F50057", "#6A1B9A",
  "#880E4F", "#673AB7", "#303F9F", "#0D47A1", "#607D8B", "#2E7D32",
  "#00695C", "#01579B", "#FF6F00", "#424242", "#FF5722", "#BF360C",
  "#795548", "#E65100", "#6200EA", "#9C27B0", "#9E9D24", "#263238",
  "#d50000", "#0D47A1", "#4A148C", "#3E2723", "#00695C", "#827717",

  			 "#b71c1c", "#006064", "#C51162", "#F50057", "#6A1B9A",
  "#880E4F", "#673AB7", "#303F9F", "#0D47A1", "#607D8B", "#2E7D32",
  "#00695C", "#01579B", "#FF6F00", "#424242", "#FF5722", "#BF360C",
  "#795548", "#E65100", "#6200EA", "#9C27B0", "#9E9D24", "#263238",
  "#d50000", "#0D47A1", "#4A148C", "#3E2723", "#00695C", "#827717"];

var score = 0;
var seconds;
var temp;
var randomBox;
var col;
var opacy = 0.77;

var factorial = function (number){
	if (number ===0 || number === 1)
		return 1;
	return factorial(number-1)*number;
};

var index = 0;
var help = false;

var bigbox = document.getElementById("bigbox");
var boxH = getComputedStyle(bigbox).getPropertyValue("height");

var max_size = factorial(Math.max(...boxes));
var bigBoxSize = boxH.slice(0,boxH.length - 2);

function createSmallBox(total_extra_space, no_of_box){

	var h = bigBoxSize - total_extra_space;

	console.log(h);

	h = h/no_of_box + "px";

	var SmallBox = document.createElement("div");

	SmallBox.id = "SmallBox";
	SmallBox.style.backgroundColor = col;
	SmallBox.style.height = h;
	SmallBox.style.width = h;
	bigbox.appendChild(SmallBox);
}

function scoreUpdater () {
	 ScoreDiv = document.getElementById("score");
	 ScoreDiv.innerHTML = "Score: " + score;
}

function randomBoxSelector() {
	 var allChilds = bigbox.childNodes;
	 randomBox = allChilds[Math.floor((Math.random() * (boxes[index]*boxes[index])))];
	 randomBox.style.opacity = opacy;

	 if(index % 2 == 0)
		{
			opacy = opacy + 0.004;
		}

		 randomBox.onclick = function (){
	 	 if(index == 1){
	 	 	document.getElementById('countdown').innerHTML = 60 + 1;
	 	 	 //Set the time here.
	 	 	countdown();
	 	 }
	 	 score++;
	 	 scoreUpdater();
	 	 start();
	 }
}

function create(){
	col = colrs[Math.floor((Math.random() * (colrs.length)))];
	for(var i=0; i<boxes[index]*boxes[index]; i++){
		var extra_spaces = 6 * boxes[index];
		createSmallBox(extra_spaces, boxes[index]);
	}
	randomBoxSelector();
}

function scoreplay () {
	 bigbox.style.backgroundColor = "black";
	 bigbox.style.fontSize = bigBoxSize * 0.13 + "px";
	 bigbox.style.color = "white";
	 bigbox.style.textAlign = "center";
	 bigbox.style.fontFamily = "'Passion One', cursive, sans-serif";

	 bigbox.innerHTML = "

Your Score: " + score;

	 bigbox.innerHTML = bigbox.innerHTML + "

 Tap to Replay";

	 bigbox.onclick = function () {
	 	 location.reload();
	 }

}

function countdown() {
	seconds = document.getElementById('countdown').innerHTML;
	seconds = parseInt(seconds, 10);

	if (seconds == 1) {
		temp = document.getElementById('countdown');
		temp.innerHTML = "Game Over";
		randomBox.style.backgroundColor = "black";
		randomBox.onclick = null;
		scoreplay();
		// window.alert("Your Score = " + score);
		}

	seconds--;
        if (seconds === 0){
            var game_over = document.getElementById("game_over");
            game_over.play();
        }
        else{
	    var tick = document.getElementById('tick');
	    tick.volume = Math.max((60 - seconds) / 60, 0.5);
	    tick.play();
        }
	temp = document.getElementById('countdown');
	temp.innerHTML = seconds;
	timeoutMyOswego = setTimeout(countdown, 1000);
}

function start(){
	if(index >= boxes.length)
		window.alert("Either you found a hack or you are GOD. Your Score = " + score);
		//This won't happen. let the player have no limits
	else{
		var bigBox = document.getElementById('bigbox');
		while(bigBox.firstChild){
			bigBox.removeChild(bigBox.firstChild);
		}
		create();
		index++;
	}
}

window.onload = function () {
	start();
};

window.onresize = function () {
	location.reload();
};

var populate_help = function () {
	var help_obj = document.getElementById("help");
	var help_obj_div = document.createElement('div');
	help_obj_div.id = "help-text";

	help_obj_text = "
Society is always hard on the odd ones and so is this game. Seperate as many odd boxes from the matrix as you can while the Timer is still ticking.
"+
					"
Try to differentiate as fast as you can to check your reflexes and sense of judgement.
" +
					"
By: htadg
";

	help_obj_div.innerHTML += help_obj_text;

	help_obj.appendChild(help_obj_div);
};

var help_height = $("#help").height();
var help_width = $("#help").width();

$("#help").click(function () {
	if (!help){
		$("#help").animate({
			height: "240px",
			width: "300px"
		}, 500);
		populate_help();
		help = true;
	}
	else{
		$("#help-text").remove();
		$('#help').animate({
			height: ""+help_height+"px",
			width: ""+help_width+"px"
		}, 500);
		help = false;
	}
});

var leaderboard;

function createCORSRequest (method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else{
        xhr = null;
    }
    return xhr;
}

function getLeaderBoard () {
    var url = "http://kube-server.herokuapp.com/score/api/v1/get";
    var xhr = createCORSRequest('GET', url);
    if (!xhr){
        alert('Please Update your Browser.');
        return;
    }
    xhr.onload = function () {
        console.log(xhr.responseText);
        leaderboard = xhr.responseText;
    };
    xhr.onerror = function () {
        console.log('Woops, there was an error making the request.');
    };
    xhr.withCredentials = true;
    xhr.send();
}

$("#leaderboard").click(function () {
    var leaderboard = leaderboard || getLeaderBoard();
    if(!leaderboard)
        console.log('Getting Data from Server...');
});

<|endoftext|>


<commit_before>/*
* 1) Create a variable referencing div#log. In addition to using console.log()
* you will also write the results of this program to the DOM
*/
var first = document.getElementById("log");
console.log(first);

/**
* 2) Create a variable for your name, then log in to the console
*	AND to the #log div (in a new paragraph). USE THE VARIABLE YOU CREATED ABOVE
* TO REFERENCE THE DIV. Required format: "Hello, my name is {name}."
*/
var name = "Melvin";
console.log(name);
var para2 = document.createElement("p");
var txt2 = "Hello, my name is " + name;
para2.innerHTML = txt2;

first.appendChild(para2);

/**
*	3) Create a variable referring to p#lede above.
* 4) Change the CSS class of p#lede to make it stand out in some way.
* You will obviously need to create the corresponding CSS. Once you do that,
* log (both to the console AND to the div#log in a new paragraph): "I just changed
* the class of p#lede."
*/
var second = document.getElementById("lede");
second.className = "red";
console.log("I just changed the class of p#lede");
var para = document.createElement("p");
var txt = "I just changed the class of p#lede";
para.innerHTML = txt;

first.appendChild(para);

/**
* 5) Create two more variables for the number 50 and the number 25.
* 6) Creat a variable for the product of these two variables.
*	7) Log the product of the two vars,
* in the following format: "{num1} times {num2} equals {product}."
*/

var firstNum = 50;
var secondNum = 25;

var solution = firstNum * secondNum;
console.log(solution);

/**
* 8) Create a variable for the SUM of the two numbers. Log it in the same format as
* above.
*/var sum = firstNum + secondNum;
console.log(sum);

/**
* 9) Log an h3 to the div#log (don't need to console.log() this one). It should
* say "Age Calculation Below!"
*/
var headerThree = document.createElement("h3");
var txtThree = "Age Calculation Below";
headerThree.innerHTML = txtThree;

first.appendChild(headerThree);

/**
* 10) Create two more variables: one for the current year,
* another for your birth year. Log them both in the appropate format:"The current
* year is {currentyear}. My birth year is {birthyear}" **/

var currYear = 2016;
var birthYear = 1996;
console.log("year is " + currYear + ". My birth year is " + birthYear);

/** 11) Create a variable for the difference between the current year and your birth
* year. Log that variable: "The difference between {currentyear} and {birthyear} is
* {difference}."**/

var diff = currYear - birthYear;
console.log("The difference between " + currYear + " and " + birthYear + " is " +diff );

/* 12) Based on this calcuation, you could be one of two ages. Use math to create
* another variable for your OTHER possible age. Log it like this. "I could be
* {difference} or {otherage} years old."
*/
var other = 19;
console.log("I could be " + diff + " or " + other + " years old");
/**
* 13) Finally, based on the Module 3 readings, tell me the ways in which
* functions would have made this exercise easier. Log it.
**/

console.log("We could have written functions for everything we copied and pasted instead only switching out the variables. Especially creating a new paragraph each time.")<commit_msg>Final<commit_after>/*
* 1) Create a variable referencing div#log. In addition to using console.log()
* you will also write the results of this program to the DOM
*/
var first = document.getElementById("log");
console.log(first);

/**
* 2) Create a variable for your name, then log in to the console
*	AND to the #log div (in a new paragraph). USE THE VARIABLE YOU CREATED ABOVE
* TO REFERENCE THE DIV. Required format: "Hello, my name is {name}."
*/
var name = "Melvin";
console.log(name);
var para2 = document.createElement("p");
var txt2 = "Hello, my name is " + name;
para2.innerHTML = txt2;

first.appendChild(para2);

/**
*	3) Create a variable referring to p#lede above.
* 4) Change the CSS class of p#lede to make it stand out in some way.
* You will obviously need to create the corresponding CSS. Once you do that,
* log (both to the console AND to the div#log in a new paragraph): "I just changed
* the class of p#lede."
*/
var second = document.getElementById("lede");
second.className = "red";
console.log("I just changed the class of p#lede");
var para = document.createElement("p");
var txt = "I just changed the class of p#lede";
para.innerHTML = txt;

first.appendChild(para);

/**
* 5) Create two more variables for the number 50 and the number 25.
* 6) Creat a variable for the product of these two variables.
*	7) Log the product of the two vars,
* in the following format: "{num1} times {num2} equals {product}."
*/

var firstNum = 50;
var secondNum = 25;

var solution = firstNum * secondNum;
console.log(solution);

/**
* 8) Create a variable for the SUM of the two numbers. Log it in the same format as
* above.
*/var sum = firstNum + secondNum;
console.log(sum);

/**
* 9) Log an h3 to the div#log (don't need to console.log() this one). It should
* say "Age Calculation Below!"
*/
var headerThree = document.createElement("h3");
var txtThree = "Age Calculation Below";
headerThree.innerHTML = txtThree;

first.appendChild(headerThree);

/**
* 10) Create two more variables: one for the current year,
* another for your birth year. Log them both in the appropate format:"The current
* year is {currentyear}. My birth year is {birthyear}" **/

var currYear = 2016;
var birthYear = 1996;
console.log("year is " + currYear + ". My birth year is " + birthYear);

var p3 = document.createElement("p");
var txtFour = "year is " + currYear + ". My birth year is " + birthYear;
p3.innerHTML = txtFour;
first.appendChild(p3);

/** 11) Create a variable for the difference between the current year and your birth
* year. Log that variable: "The difference between {currentyear} and {birthyear} is
* {difference}."**/

var diff = currYear - birthYear;
console.log("The difference between " + currYear + " and " + birthYear + " is " +diff );

var p4 = document.createElement("p");
var txtFive = "The difference between " + currYear + " and " + birthYear + " is " +diff;
p4.innerHTML = txtFive;
first.appendChild(p4);

/* 12) Based on this calcuation, you could be one of two ages. Use math to create
* another variable for your OTHER possible age. Log it like this. "I could be
* {difference} or {otherage} years old."
*/
var other = 19;
console.log("I could be " + diff + " or " + other + " years old");

var p5 = document.createElement("p");
var txtSix = "I could be " + diff + " or " + other + " years old";
p5.innerHTML = txtSix;
first.appendChild(p5);

/**

* 13) Finally, based on the Module 3 readings, tell me the ways in which
* functions would have made this exercise easier. Log it.
**/

console.log("We could have written functions for everything we copied and pasted instead only switching out the variables. Especially creating a new paragraph each time.")<|endoftext|>


<commit_before>var onEatAudio = new Audio('src/onEat.wav');
var onLoseAudio = new Audio('src/onLose.wav');
var UNIT = 30;
var CANVAS_WIDTH = 16 * UNIT;
var CANVAS_HEIGHT = 16 * UNIT;
var score = 0;
var bestScore = 0;
var canvasElement = $("<canvas class='blur' width='" + CANVAS_WIDTH +
                      "' height='" + CANVAS_HEIGHT + "'>Your browser does not support the HTML5 canvas tag.</canvas>");
var canvas = canvasElement.get(0).getContext("2d");
var FPS = 30;
var paused = false;
$(document).ready(function(){
  canvasElement.appendTo('#canvas_container'); // create canvas in body
  setInterval(function() {
    update();
    draw();
  }, 1000/FPS); // set FPS
});
// var period = 20;
var period = 3;
var moveLeft;
var moveRight;
var moveUp;
var moveDown;
var currentDirection;
var timer = period;
var bodies = new Array();
var swipeDirection;
var ratio = 50;
var onGoing = false;
var touchEvent;
function move(){
  $("body").swipe({
    swipe:function(event, direction, distance, duration, fingerCount) {
      touchEvent = event;
      swipeDirection = direction;
    }
  });
  // check keys
  if (onGoing) {
    if ((keydown.left || keydown.a || swipeDirection == "left") && (currentDirection != "right" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = true;
      moveRight = false;
      moveUp = false;
      moveDown = false;
      swipeDirection = "left";
      paused = false;
    }
    if ((keydown.right || keydown.d || swipeDirection == "right") && (currentDirection != "left" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = false;
      moveRight = true;
      moveUp = false;
      moveDown = false;
      swipeDirection = "right";
      paused = false;
    }
    if ((keydown.up || keydown.w || swipeDirection == "up") && (currentDirection != "down" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = false;
      moveRight = false;
      moveUp = true;
      moveDown = false;
      swipeDirection = "up";
      paused = false;
    }
    if ((keydown.down || keydown.s || swipeDirection == "down") && (currentDirection != "up" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = false;
      moveRight = false;
      moveUp = false;
      moveDown = true;
      swipeDirection = "down";
      paused = false;
    }
    if ((keydown.space || touchEvent == "in" || touchEvent == "out" )&& !paused) {
      paused = !paused;
      console.log(paused);
      moveLeft = false;
      moveRight = false;
      moveUp = false;
      moveDown = false;
      swipeDirection = null;
      $("canvas").addClass('blur');
      document.getElementById("pause").style.display = "block";
    }
  }

  if (paused) {
    timer = period;
  }
  // move accordingly
  if (timer==0) {
      for (var i=bodyNum; i>0;i--) {
//        if (i==0) {
//          bodies[i] = new body(head.x-UNIT/2, head.y-UNIT/2);
//        } else {
        bodies[i] = new body(bodies[i-1].x,bodies[i-1].y);
//      }
      }
      bodies[0] = new body(head.x-UNIT/2, head.y-UNIT/2);

    timer = period;
//    body(head.x - UNIT/2, head.y - UNIT/2);

    if (!paused) {
      if (moveLeft) {
        currentDirection = "left";
        head.x -= UNIT;
      } else if (moveRight) {
        currentDirection = "right";
        head.x += UNIT;
      } else if (moveUp) {
        currentDirection = "up";
        head.y -= UNIT;
      } else if (moveDown) {
        currentDirection = "down";
        head.y += UNIT;
      }
    }
  }
  timer--;

}

function edge() {
  if (head.x<0) {
    head.x += CANVAS_WIDTH;
  } else if (head.x>CANVAS_WIDTH) {
    head.x -= CANVAS_WIDTH;
  }
  if (head.y<0) {
    head.y += CANVAS_HEIGHT;
  } else if (head.y>CANVAS_HEIGHT) {
    head.y -= CANVAS_HEIGHT;
  }
}

var recheck;
var bodyNum = 0;
var got = false;
function checkGot() {
  if (food.x == head.x && food.y == head.y) {
    got = true;
  }
  if (got) {
    score += ratio;
    onEatAudio.play();
    if (score >= bestScore) {
      bestScore = score;
    }
    bodyNum++;
    food.x = UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5;
    food.y = UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5;
    recheck = true;
    while (recheck == true) {
      recheck = false;
      console.log(recheck)
    for (var i=0; i<bodyNum;i++) {
      if (bodies[i].x==food.x-UNIT/2 && bodies[i].y==food.y-UNIT/2) {
        food.x = UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5;
          food.y = UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5;
          recheck = true;
      }
    }
  }
    got = false;
  }
}

var die = false;
function checkDie(){
  if (!die) {
    for (var i=0; i<bodyNum;i++) {
      if (bodies[i].x==head.x-UNIT/2 && bodies[i].y==head.y-UNIT/2) {
          die = true;
          paused = true;
          onGoing = false;
          onLoseAudio.play();
          document.getElementById("game_over").style.display = "block";
          $("canvas").addClass('blur');
          $("#info_container").removeClass('glass');
      }
    }
  }
}

// update
function update() {
  if (!die) {
    updateScores();
    move();
    edge();
    checkGot();
  }
  checkDie();
}

function updateScores() {
  document.getElementById("score").innerHTML = score;
  document.getElementById("best").innerHTML = bestScore;

}

// draw
function draw() {
  canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  canvas.lineWidth = 4;
  canvas.strokeStyle = 'rgba(41, 98, 255, 0.2)';
  // if (!die){
    food.draw();
    head.draw();
    for (var i=0; i<bodyNum;i++) {
      bodies[i].draw();
  }
  // } else {
  //   canvas.fillStyle = "#0d47a1";
  //   canvas.fillText("SCORE:"+score, CANVAS_WIDTH/2, CANVAS_HEIGHT/2-10);
  //   canvas.fillText("GAME OVER!", CANVAS_WIDTH/2, CANVAS_HEIGHT/2);
  // }
}

var head = {
  color: "rgba(41, 98, 255, 0.5)",
  x: UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5,
  y: UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5,
  r: UNIT/2,
  draw: function() {
    canvas.fillStyle = this.color;
    rectX = this.x-UNIT/2;
    rectY = this.y-UNIT/2;
    cornerRadius = 8;
    canvas.beginPath();
    canvas.moveTo(rectX + cornerRadius, rectY);
    canvas.lineTo(rectX + UNIT - cornerRadius, rectY);
    canvas.arcTo(rectX + UNIT, rectY, rectX + UNIT, rectY + cornerRadius, cornerRadius);
    canvas.lineTo(rectX + UNIT, rectY + UNIT - cornerRadius);
    canvas.arcTo(rectX + UNIT, rectY + UNIT, rectX + UNIT - cornerRadius, rectY + UNIT, cornerRadius);
    canvas.lineTo(rectX + cornerRadius, rectY + UNIT);
    canvas.arcTo(rectX, rectY + UNIT, rectX, rectY + UNIT - cornerRadius, cornerRadius);
    canvas.lineTo(rectX, rectY + cornerRadius);
    canvas.arcTo(rectX, rectY, rectX + cornerRadius, rectY, cornerRadius);
    canvas.fill();
    // canvas.stroke();
    // canvas.fillStyle = '#0d47a1';
    // canvas.beginPath();
    // canvas.arc(this.x, this.y, 3, 0, 2*Math.PI);
    // canvas.fill();
    // canvas.stroke();
  }
};

function body(tempX,tempY) {
  this.x = tempX;
  this.y = tempY;
  this.draw = function() {
    rectX = this.x;
    rectY = this.y;
    cornerRadius = 8;
    canvas.fillStyle = 'rgba(41, 98, 255, 0.5)';
    canvas.beginPath();
    canvas.moveTo(rectX + cornerRadius, rectY);
    canvas.lineTo(rectX + UNIT - cornerRadius, rectY);
    canvas.arcTo(rectX + UNIT, rectY, rectX + UNIT, rectY + cornerRadius, cornerRadius);
    canvas.lineTo(rectX + UNIT, rectY + UNIT - cornerRadius);
    canvas.arcTo(rectX + UNIT, rectY + UNIT, rectX + UNIT - cornerRadius, rectY + UNIT, cornerRadius);
    canvas.lineTo(rectX + cornerRadius, rectY + UNIT);
    canvas.arcTo(rectX, rectY + UNIT, rectX, rectY + UNIT - cornerRadius, cornerRadius);
    canvas.lineTo(rectX, rectY + cornerRadius);
    canvas.arcTo(rectX, rectY, rectX + cornerRadius, rectY, cornerRadius);
    canvas.fill();
    // canvas.stroke();
  };
}

var food = {
  color: "rgba(41, 98, 255, 0.9)",
  x: UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5,
  y: UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5,
  r: UNIT/2,
  draw: function() {
    canvas.fillStyle = this.color;
    canvas.beginPath();
    canvas.arc(this.x,this.y,this.r, 0,2*Math.PI);
    canvas.fill();
    // canvas.stroke();
  }
};

// button controls
$(document).ready(function(){
  $("#easy").click(function(){
    period = 15;
    ratio = 10;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("canvas").removeClass('blur');
    $("#info_container").removeClass('glass');
  });
  $("#hard").click(function(){
    period = 5;
    ratio = 30;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("#info_container").removeClass('glass');
    $("canvas").removeClass('blur');
  });
  $("#insane").click(function(){
    period = 3;
    ratio = 50;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("#info_container").removeClass('glass');
    $("canvas").removeClass('blur');
  });
  $("#crazy").click(function(){
    period = 1;
    ratio = 150;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("#info_container").removeClass('glass');
    $("canvas").removeClass('blur');
  });
  $("#resume").click(function(){
    document.getElementById("pause").style.display = "none";
    $("canvas").removeClass('blur');
  });
  $("#restart").click(function(){
    die = false;
    bodyNum = 0;
    score = 0;
    moveUp = false;
    moveDown = false;
    moveLeft = false;
    moveDown = false;
    swipeDirection = " ";
    document.getElementById("game_over").style.display = "none";
    document.getElementById("difficulties").style.display = "block";
  });
});

// prevent scrolling with arrow keys
document.onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    if (keyCode >= 37 && keyCode <= 40 || keyCode == 32) {
        return false;
    }
};<commit_msg>bug fixed two-finger touch to pause<commit_after>var onEatAudio = new Audio('src/onEat.wav');
var onLoseAudio = new Audio('src/onLose.wav');
var UNIT = 30;
var CANVAS_WIDTH = 16 * UNIT;
var CANVAS_HEIGHT = 16 * UNIT;
var score = 0;
var bestScore = 0;
var canvasElement = $("<canvas class='blur' width='" + CANVAS_WIDTH +
                      "' height='" + CANVAS_HEIGHT + "'>Your browser does not support the HTML5 canvas tag.</canvas>");
var canvas = canvasElement.get(0).getContext("2d");
var FPS = 30;
var paused = false;
$(document).ready(function(){
  canvasElement.appendTo('#canvas_container'); // create canvas in body
  setInterval(function() {
    update();
    draw();
  }, 1000/FPS); // set FPS
});
// var period = 20;
var period = 3;
var moveLeft;
var moveRight;
var moveUp;
var moveDown;
var currentDirection;
var timer = period;
var bodies = new Array();
var swipeDirection;
var ratio = 50;
var onGoing = false;
var fingerNumber;
function move(){
  $("body").swipe({
    swipe:function(event, direction, distance, duration, fingerCount) {
      fingerNumber = fingerCount;
      swipeDirection = direction;
    }
  });
  // check keys
  if (onGoing) {
    if ((keydown.left || keydown.a || swipeDirection == "left") && (currentDirection != "right" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = true;
      moveRight = false;
      moveUp = false;
      moveDown = false;
      swipeDirection = "left";
      paused = false;
    }
    if ((keydown.right || keydown.d || swipeDirection == "right") && (currentDirection != "left" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = false;
      moveRight = true;
      moveUp = false;
      moveDown = false;
      swipeDirection = "right";
      paused = false;
    }
    if ((keydown.up || keydown.w || swipeDirection == "up") && (currentDirection != "down" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = false;
      moveRight = false;
      moveUp = true;
      moveDown = false;
      swipeDirection = "up";
      paused = false;
    }
    if ((keydown.down || keydown.s || swipeDirection == "down") && (currentDirection != "up" || bodyNum == 0)) {
      $("canvas").removeClass('blur');
      moveLeft = false;
      moveRight = false;
      moveUp = false;
      moveDown = true;
      swipeDirection = "down";
      paused = false;
    }
    if ((keydown.space || fingerNumber == 2)&& !paused) {
      paused = !paused;
      console.log(paused);
      moveLeft = false;
      moveRight = false;
      moveUp = false;
      moveDown = false;
      swipeDirection = null;
      $("canvas").addClass('blur');
      document.getElementById("pause").style.display = "block";
    }
  }

  if (paused) {
    timer = period;
  }
  // move accordingly
  if (timer==0) {
      for (var i=bodyNum; i>0;i--) {
//        if (i==0) {
//          bodies[i] = new body(head.x-UNIT/2, head.y-UNIT/2);
//        } else {
        bodies[i] = new body(bodies[i-1].x,bodies[i-1].y);
//      }
      }
      bodies[0] = new body(head.x-UNIT/2, head.y-UNIT/2);

    timer = period;
//    body(head.x - UNIT/2, head.y - UNIT/2);

    if (!paused) {
      if (moveLeft) {
        currentDirection = "left";
        head.x -= UNIT;
      } else if (moveRight) {
        currentDirection = "right";
        head.x += UNIT;
      } else if (moveUp) {
        currentDirection = "up";
        head.y -= UNIT;
      } else if (moveDown) {
        currentDirection = "down";
        head.y += UNIT;
      }
    }
  }
  timer--;

}

function edge() {
  if (head.x<0) {
    head.x += CANVAS_WIDTH;
  } else if (head.x>CANVAS_WIDTH) {
    head.x -= CANVAS_WIDTH;
  }
  if (head.y<0) {
    head.y += CANVAS_HEIGHT;
  } else if (head.y>CANVAS_HEIGHT) {
    head.y -= CANVAS_HEIGHT;
  }
}

var recheck;
var bodyNum = 0;
var got = false;
function checkGot() {
  if (food.x == head.x && food.y == head.y) {
    got = true;
  }
  if (got) {
    score += ratio;
    onEatAudio.play();
    if (score >= bestScore) {
      bestScore = score;
    }
    bodyNum++;
    food.x = UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5;
    food.y = UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5;
    recheck = true;
    while (recheck == true) {
      recheck = false;
      console.log(recheck)
    for (var i=0; i<bodyNum;i++) {
      if (bodies[i].x==food.x-UNIT/2 && bodies[i].y==food.y-UNIT/2) {
        food.x = UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5;
          food.y = UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5;
          recheck = true;
      }
    }
  }
    got = false;
  }
}

var die = false;
function checkDie(){
  if (!die) {
    for (var i=0; i<bodyNum;i++) {
      if (bodies[i].x==head.x-UNIT/2 && bodies[i].y==head.y-UNIT/2) {
          die = true;
          paused = true;
          onGoing = false;
          onLoseAudio.play();
          document.getElementById("game_over").style.display = "block";
          $("canvas").addClass('blur');
          $("#info_container").removeClass('glass');
      }
    }
  }
}

// update
function update() {
  if (!die) {
    updateScores();
    move();
    edge();
    checkGot();
  }
  checkDie();
}

function updateScores() {
  document.getElementById("score").innerHTML = score;
  document.getElementById("best").innerHTML = bestScore;

}

// draw
function draw() {
  canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  canvas.lineWidth = 4;
  canvas.strokeStyle = 'rgba(41, 98, 255, 0.2)';
  // if (!die){
    food.draw();
    head.draw();
    for (var i=0; i<bodyNum;i++) {
      bodies[i].draw();
  }
  // } else {
  //   canvas.fillStyle = "#0d47a1";
  //   canvas.fillText("SCORE:"+score, CANVAS_WIDTH/2, CANVAS_HEIGHT/2-10);
  //   canvas.fillText("GAME OVER!", CANVAS_WIDTH/2, CANVAS_HEIGHT/2);
  // }
}

var head = {
  color: "rgba(41, 98, 255, 0.5)",
  x: UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5,
  y: UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5,
  r: UNIT/2,
  draw: function() {
    canvas.fillStyle = this.color;
    rectX = this.x-UNIT/2;
    rectY = this.y-UNIT/2;
    cornerRadius = 8;
    canvas.beginPath();
    canvas.moveTo(rectX + cornerRadius, rectY);
    canvas.lineTo(rectX + UNIT - cornerRadius, rectY);
    canvas.arcTo(rectX + UNIT, rectY, rectX + UNIT, rectY + cornerRadius, cornerRadius);
    canvas.lineTo(rectX + UNIT, rectY + UNIT - cornerRadius);
    canvas.arcTo(rectX + UNIT, rectY + UNIT, rectX + UNIT - cornerRadius, rectY + UNIT, cornerRadius);
    canvas.lineTo(rectX + cornerRadius, rectY + UNIT);
    canvas.arcTo(rectX, rectY + UNIT, rectX, rectY + UNIT - cornerRadius, cornerRadius);
    canvas.lineTo(rectX, rectY + cornerRadius);
    canvas.arcTo(rectX, rectY, rectX + cornerRadius, rectY, cornerRadius);
    canvas.fill();
    // canvas.stroke();
    // canvas.fillStyle = '#0d47a1';
    // canvas.beginPath();
    // canvas.arc(this.x, this.y, 3, 0, 2*Math.PI);
    // canvas.fill();
    // canvas.stroke();
  }
};

function body(tempX,tempY) {
  this.x = tempX;
  this.y = tempY;
  this.draw = function() {
    rectX = this.x;
    rectY = this.y;
    cornerRadius = 8;
    canvas.fillStyle = 'rgba(41, 98, 255, 0.5)';
    canvas.beginPath();
    canvas.moveTo(rectX + cornerRadius, rectY);
    canvas.lineTo(rectX + UNIT - cornerRadius, rectY);
    canvas.arcTo(rectX + UNIT, rectY, rectX + UNIT, rectY + cornerRadius, cornerRadius);
    canvas.lineTo(rectX + UNIT, rectY + UNIT - cornerRadius);
    canvas.arcTo(rectX + UNIT, rectY + UNIT, rectX + UNIT - cornerRadius, rectY + UNIT, cornerRadius);
    canvas.lineTo(rectX + cornerRadius, rectY + UNIT);
    canvas.arcTo(rectX, rectY + UNIT, rectX, rectY + UNIT - cornerRadius, cornerRadius);
    canvas.lineTo(rectX, rectY + cornerRadius);
    canvas.arcTo(rectX, rectY, rectX + cornerRadius, rectY, cornerRadius);
    canvas.fill();
    // canvas.stroke();
  };
}

var food = {
  color: "rgba(41, 98, 255, 0.9)",
  x: UNIT*Math.floor(Math.random()*(CANVAS_WIDTH/UNIT-1))+UNIT*0.5,
  y: UNIT*Math.floor(Math.random()*(CANVAS_HEIGHT/UNIT-1))+UNIT*0.5,
  r: UNIT/2,
  draw: function() {
    canvas.fillStyle = this.color;
    canvas.beginPath();
    canvas.arc(this.x,this.y,this.r, 0,2*Math.PI);
    canvas.fill();
    // canvas.stroke();
  }
};

// button controls
$(document).ready(function(){
  $("#easy").click(function(){
    period = 15;
    ratio = 10;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("canvas").removeClass('blur');
    $("#info_container").removeClass('glass');
  });
  $("#hard").click(function(){
    period = 5;
    ratio = 30;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("#info_container").removeClass('glass');
    $("canvas").removeClass('blur');
  });
  $("#insane").click(function(){
    period = 3;
    ratio = 50;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("#info_container").removeClass('glass');
    $("canvas").removeClass('blur');
  });
  $("#crazy").click(function(){
    period = 1;
    ratio = 150;
    onGoing = true;
    document.getElementById("difficulties").style.display = "none";
    $("#info_container").removeClass('glass');
    $("canvas").removeClass('blur');
  });
  $("#resume").click(function(){
    document.getElementById("pause").style.display = "none";
    $("canvas").removeClass('blur');
  });
  $("#restart").click(function(){
    die = false;
    bodyNum = 0;
    score = 0;
    moveUp = false;
    moveDown = false;
    moveLeft = false;
    moveDown = false;
    swipeDirection = " ";
    document.getElementById("game_over").style.display = "none";
    document.getElementById("difficulties").style.display = "block";
  });
});

// prevent scrolling with arrow keys
document.onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    if (keyCode >= 37 && keyCode <= 40 || keyCode == 32) {
        return false;
    }
};<|endoftext|>


<commit_before>(function() {

  function JsonInputView(el) {
    this.el = el;
    var codemirror = this.codemirror = CodeMirror.fromTextArea(this.el, {
      lineNumbers: true,
      mode: {name: "javascript", json: true},
      theme: 'tomorrow-night'
    });
    var self = this;

    codemirror.on('inputRead', function (cm, e) {
      if (e.origin === 'paste') {
        autoFormat();
      }
      triggerChange();
    });
    codemirror.on('keyup', triggerChange);
    codemirror.on('change', triggerChange);
    codemirror.on('clear', function () {
      console.log(arguments);
    });

    var oldValue = '';
    function triggerChange() {
      var text = codemirror.getValue();
        if (text !== oldValue) {
          self.trigger('change');
        }
      oldValue = text;
    }

    function autoFormat() {
      var totalLines = codemirror.lineCount();
      codemirror.autoFormatRange({line:0, ch:0}, {line:totalLines});
      codemirror.setSelection({line:0, ch:0});
    }
  }

  JsonInputView.prototype.getText = function () {
    return this.codemirror.getValue();
  };

  JsonInputView.prototype.highlightRemoval = function (diff) {
    this._highlight(diff, '#DD4444');
  };

  JsonInputView.prototype.highlightAddition = function (diff) {
    this._highlight(diff, '#2E6DFF');
  };

  JsonInputView.prototype.highlightChange = function (diff) {
    this._highlight(diff, '#9E9E00');
  };

  JsonInputView.prototype._highlight = function (diff, className) {
    var pos = getStartAndEndPosOfDiff(this.getText(), diff);
    this.codemirror.markText(pos.start, pos.end, {
      css: 'background-color: ' + className
    });
  }

  JsonInputView.prototype.clearMarkers = function () {
    this.codemirror.getAllMarks().forEach(function (marker) {
      marker.clear();
    });
  }

  function getStartAndEndPosOfDiff(textValue, diff) {
    var findPath = diff.path;
    var contexts = {
      ARRAY: 'ARRAY',
      OBJECT: 'OBJECT'
    };
    var QUOTE = '"';
    var OBJ_OPEN = '{';
    var OBJ_CLOSE = '}';
    var ARR_OPEN = '[';
    var ARR_CLOSE = ']';
    var SEPARATOR = ',';
    var ESCAPE = '\\';
    var NL = '\n';
    var OBJ_PROPERTY_RGX = /^"([^"]|\\")*"(?=\s*:)/g;
    var startPos, endPos, currChar, prevChar, currPath = [], contextStack = [], line = 0, ch = 0, inString = false;
    for (var i = 0; i < textValue.length; i++) {
      ch++;
      currChar = textValue[i];
      if (currChar === NL) {
        line++;
        ch = 0;
      } else if (currChar === OBJ_OPEN) {
        currPath.push(null);
        contextStack.push(contexts.OBJECT);
      } else if (currChar === ARR_OPEN) {
        currPath.push(0);
        contextStack.push(contexts.ARRAY);
      } else if (currChar === QUOTE && !inString && prevChar !== ESCAPE) {
        inString = true;
        var prop = getNextObjProperty(i);
        if (prop) {
          currPath.push(prop);
        }
      } else if (currChar === SEPARATOR && !inString) {
        if (context() === contexts.ARRAY) {
          var currArrayIdx = currPath[currPath.length - 1];
          currArrayIdx  = typeof(currArrayIdx ) === 'number' ? currArrayIdx  + 1 : 0;
          currPath.pop();
          currPath.push(currArrayIdx);
        } else {
          currPath.pop();
        }
      } else if (currChar === QUOTE && inString) {
        inString = false;
      } else if (currChar === OBJ_CLOSE) {
        contextStack.pop();
        currPath.pop();
        // look behind for empty object
        var matches = textValue.split('').reverse().join('').substr(textValue.length - i).match(/^\s*{/g) || [];
        var isEmptyObject = matches.length > 0;
        if (!isEmptyObject) {
          currPath.pop();
        }
      } else if (currChar === ARR_CLOSE) {
        contextStack.pop();
        currPath.pop();
      }

      var currPathStr = '/' + currPath.filter(function (item) {
        return item !== null;
      }).join('/');
      if (currPathStr === findPath && !startPos) {
        startPos = {
          line: line,
          ch: ch - 1
        };
      } else if (currPathStr.indexOf(findPath) === 0 && !(/\s/g).test(currChar)) {
        endPos = {
          line: line,
          ch: ch
        };
      }

      prevChar = currChar;
    }

    function getNextObjProperty(idx) {
      var matches = textValue.substr(idx).match(OBJ_PROPERTY_RGX) || [];
      var next = matches[0];
      if (next) {
        next = next.substr(1, next.length - 2);
      }
      return next;
    }

    function followedByComma(idx) {
      var matches = textValue.substr(idx + 1).match(/^\s*,/g) || [];
      return matches.length > 0;
    }

    function context() {
      return contextStack[contextStack.length - 1];
    }

    return {
      start: startPos,
      end: endPos
    }
  }

  function indexToPos(textValue, i) {
    var beginStr = textValue.substr(0, i);
    var lines = beginStr.split('\n');
    return {
      line: lines.length - 1,
      ch: lines[lines.length - 1].length
    };
  }

  BackboneEvents.mixin(JsonInputView.prototype);

  var leftInputView = new JsonInputView(document.getElementById('json-diff-left'));
  var rightInputView = new JsonInputView(document.getElementById('json-diff-right'));
  leftInputView.on('change', compareJson);
  rightInputView.on('change', compareJson);
  leftInputView.codemirror.on('scroll', function () {
    var scrollInfo = leftInputView.codemirror.getScrollInfo();
    rightInputView.codemirror.scrollTo(scrollInfo.left, scrollInfo.top);
  });
  rightInputView.codemirror.on('scroll', function () {
    var scrollInfo = rightInputView.codemirror.getScrollInfo();
    leftInputView.codemirror.scrollTo(scrollInfo.left, scrollInfo.top);
  });

  function compareJson() {
    leftInputView.clearMarkers();
    rightInputView.clearMarkers();
    var leftText = leftInputView.getText(), rightText = rightInputView.getText();
    var leftJson, rightJson;
    try {
      if (leftText) {
        leftJson = JSON.parse(leftText);
      }
      if (rightText) {
        rightJson = JSON.parse(rightText);
      }
      document.getElementById('error-message').style.display = 'none';
    } catch (e) {
      document.getElementById('error-message').style.display = 'inline-block';
    }
    if (!leftJson || !rightJson) return;
    var diffs = jsonpatch.compare(leftJson, rightJson);
    console.log(diffs);
    diffs.forEach(function (diff) {
      if (diff.op === 'remove') {
        leftInputView.highlightRemoval(diff);
      } else if (diff.op === 'add') {
        rightInputView.highlightAddition(diff);
      } else if (diff.op === 'replace') {
        rightInputView.highlightChange(diff);
        leftInputView.highlightChange(diff);
      }
    });
  }

})();
<commit_msg>Update main.js<commit_after>(function() {

  function JsonInputView(el) {
    this.el = el;
    var codemirror = this.codemirror = CodeMirror.fromTextArea(this.el, {
      lineNumbers: true,
      mode: {name: "javascript", json: true},
      theme: 'tomorrow-night'
    });
    var self = this;

    codemirror.on('inputRead', function (cm, e) {
      if (e.origin === 'paste') {
        autoFormat();
      }
      triggerChange();
    });
    codemirror.on('keyup', triggerChange);
    codemirror.on('change', triggerChange);
    codemirror.on('clear', function () {
      console.log(arguments);
    });

    var oldValue = '';
    function triggerChange() {
      var text = codemirror.getValue();
        if (text !== oldValue) {
          self.trigger('change');
        }
      oldValue = text;
    }

    function autoFormat() {
      var totalLines = codemirror.lineCount();
      codemirror.autoFormatRange({line:0, ch:0}, {line:totalLines});
      codemirror.setSelection({line:0, ch:0});
    }
  }

  JsonInputView.prototype.getText = function () {
    return this.codemirror.getValue();
  };

  JsonInputView.prototype.highlightRemoval = function (diff) {
    this._highlight(diff, '#DD4444');
  };

  JsonInputView.prototype.highlightAddition = function (diff) {
    this._highlight(diff, '#2E6DFF');
  };

  JsonInputView.prototype.highlightChange = function (diff) {
    this._highlight(diff, '#9E9E00');
  };

  JsonInputView.prototype._highlight = function (diff, className) {
    var pos = getStartAndEndPosOfDiff(this.getText(), diff);
    this.codemirror.markText(pos.start, pos.end, {
      css: 'background-color: ' + className
    });
  }

  JsonInputView.prototype.clearMarkers = function () {
    this.codemirror.getAllMarks().forEach(function (marker) {
      marker.clear();
    });
  }

  function getStartAndEndPosOfDiff(textValue, diff) {
    var findPath = diff.path;
    var contexts = {
      ARRAY: 'ARRAY',
      OBJECT: 'OBJECT'
    };
    var QUOTE = '"';
    var OBJ_OPEN = '{';
    var OBJ_CLOSE = '}';
    var ARR_OPEN = '[';
    var ARR_CLOSE = ']';
    var SEPARATOR = ',';
    var ESCAPE = '\\';
    var NL = '\n';
    var OBJ_PROPERTY_RGX = /^"([^"]|\\")*"(?=\s*:)/g;
    var startPos, endPos, currChar, prevChar, currPath = [], contextStack = [], line = 0, ch = 0, inString = false;
    for (var i = 0; i < textValue.length; i++) {
      ch++;
      currChar = textValue[i];
      if (currChar === NL) {
        line++;
        ch = 0;
      } else if (currChar === OBJ_OPEN) {
        currPath.push(null);
        contextStack.push(contexts.OBJECT);
      } else if (currChar === ARR_OPEN) {
        currPath.push(0);
        contextStack.push(contexts.ARRAY);
      } else if (currChar === QUOTE && !inString && prevChar !== ESCAPE) {
        inString = true;
        var prop = getNextObjProperty(i);
        if (prop) {
          currPath.push(prop);
        }
      } else if (currChar === SEPARATOR && !inString) {
        if (context() === contexts.ARRAY) {
          var currArrayIdx = currPath[currPath.length - 1];
          currArrayIdx  = typeof(currArrayIdx ) === 'number' ? currArrayIdx  + 1 : 0;
          currPath.pop();
          currPath.push(currArrayIdx);
        } else {
          currPath.pop();
        }
      } else if (currChar === QUOTE && inString) {
        inString = false;
      } else if (currChar === OBJ_CLOSE) {
        contextStack.pop();
        currPath.pop();
        // look behind for empty object
        var matches = textValue.split('').reverse().join('').substr(textValue.length - i).match(/^\s*{/g) || [];
        var isEmptyObject = matches.length > 0;
        if (!isEmptyObject) {
          currPath.pop();
        }
      } else if (currChar === ARR_CLOSE) {
        contextStack.pop();
        currPath.pop();
      }

      var currPathStr = '/' + currPath.filter(function (item) {
        return item !== null;
      }).join('/');
      if (currPathStr === findPath && !startPos) {
        startPos = {
          line: line,
          ch: ch - 1
        };
      } else if (currPathStr.indexOf(findPath) === 0 && !(/\s/g).test(currChar)) {
        endPos = {
          line: line,
          ch: ch
        };
      }

      prevChar = currChar;
    }

    function getNextObjProperty(idx) {
      var matches = textValue.substr(idx).match(OBJ_PROPERTY_RGX) || [];
      var next = matches[0];
      if (next) {
        next = next.substr(1, next.length - 2);
      }
      return next;
    }

    function followedByComma(idx) {
      var matches = textValue.substr(idx + 1).match(/^\s*,/g) || [];
      return matches.length > 0;
    }

    function context() {
      return contextStack[contextStack.length - 1];
    }

    return {
      start: startPos,
      end: endPos
    }
  }

  function indexToPos(textValue, i) {
    var beginStr = textValue.substr(0, i);
    var lines = beginStr.split('\n');
    return {
      line: lines.length - 1,
      ch: lines[lines.length - 1].length
    };
  }

  BackboneEvents.mixin(JsonInputView.prototype);

  var leftInputView = new JsonInputView(document.getElementById('json-diff-left'));
  var rightInputView = new JsonInputView(document.getElementById('json-diff-right'));
  leftInputView.on('change', compareJson);
  rightInputView.on('change', compareJson);
  leftInputView.codemirror.on('scroll', function () {
    var scrollInfo = leftInputView.codemirror.getScrollInfo();
    rightInputView.codemirror.scrollTo(scrollInfo.left, scrollInfo.top);
  });
  rightInputView.codemirror.on('scroll', function () {
    var scrollInfo = rightInputView.codemirror.getScrollInfo();
    leftInputView.codemirror.scrollTo(scrollInfo.left, scrollInfo.top);
  });

  function compareJson() {
    leftInputView.clearMarkers();
    rightInputView.clearMarkers();
    var leftText = leftInputView.getText(), rightText = rightInputView.getText();
    var leftJson, rightJson;
    try {
      if (leftText) {
        leftJson = JSON.parse(leftText);
      }
      if (rightText) {
        rightJson = JSON.parse(rightText);
      }
      document.getElementById('error-message').style.display = 'none';
    } catch (e) {
      document.getElementById('error-message').style.display = 'inline-block';
    }
    if (!leftJson || !rightJson) return;
    var diffs = jsonpatch.compare(leftJson, rightJson);
    console.log(diffs);
    diffs.forEach(function (diff) {
      try {
        if (diff.op === 'remove') {
          leftInputView.highlightRemoval(diff);
        } else if (diff.op === 'add') {
          rightInputView.highlightAddition(diff);
        } else if (diff.op === 'replace') {
          rightInputView.highlightChange(diff);
          leftInputView.highlightChange(diff);
        }
      } catch(e) {
        console.warn('error while trying to highlight diff', e);
      }
    });
  }

})();
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014
 *  Bjoern Schiessle <schiessle@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

function displayEncryptionWarning () {

	if (!OC.Notification.isHidden()) {
		return;
	}

	$.get(
		OC.generateUrl('/apps/encryption/ajax/getStatus'),
		function( result ) {
			if (result.status === "success") {
				OC.Notification.show(result.data.message);
			}
		}
	);
}

$(document).ready(function() {
	// wait for other apps/extensions to register their event handlers and file actions
	// in the "ready" clause
	_.defer(function() {
		displayEncryptionWarning();
	});
});
<commit_msg>Revert "use a simple function - OC.Encryption is already defined - fixes #15707"<commit_after>/**
 * Copyright (c) 2014
 *  Bjoern Schiessle <schiessle@owncloud.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

/**
 * @namespace
 * @memberOf OC
 */
OC.Encryption= {
	MIGRATION_OPEN: 0,
	MIGRATION_COMPLETED: 1,
	MIGRATION_IN_PROGRESS: -1,

	displayEncryptionWarning: function () {

		if (!OC.Notification.isHidden()) {
			return;
		}

		$.get(
			OC.generateUrl('/apps/encryption/ajax/getStatus')
			,  function( result ) {
				if (result.status === "success") {
					OC.Notification.show(result.data.message);
				}
			}
		);
	}
};

$(document).ready(function() {
	// wait for other apps/extensions to register their event handlers and file actions
	// in the "ready" clause
	_.defer(function() {
		OC.Encryption.displayEncryptionWarning();
	});
});
<|endoftext|>