<commit_before>'use strict';

//Dice type arrays
var orangeDiceArray = [];
var blueDiceArray = [];
var grayDiceArray = [];
var maxRounds = 0;
var roundCount = 0;
var maxMauls = 5;
var photosToWin = 0;
var mauledFlag = false;
var scoreArray = [];
var gameArray = [];
var totalScore = 0;
var updateUser = new User();

function ThisGame(userName, score, difficulty) {
  this.userName = userName;
  this.score = score;
  this.difficulty = difficulty;
}

function User() {
  this.userName = '';
}

//Generic die constructor
function Die(maul, photo, footprint) {
  this.maul = maul;
  this.photo = photo;
  this.footprint = footprint;
  this.lastRoll = '';
}

//Method for generating random number
Die.prototype.randomNumber = function() {
  var baseNumber = Math.floor(Math.random() * (6) + 1);
  return baseNumber;
};

//Orange die constructor (hardest)
function Orange() {}
Orange.prototype = new Die(3,1,2);
//Blue die constructor (easiest)
function Blue() {}
Blue.prototype = new Die(1,3,2);
//Gray die constructor (medium)
function Gray() {}
Gray.prototype = new Die(2,2,2);

//Roll method for the orange dice
Orange.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2 || random === 3) {
    result = 'claw.png';
  } else if (random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};
//Roll method for the blue dice
Blue.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1) {
    result = 'claw.png';
  } else if (random === 2 || random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};
//Roll method for the gray dice
Gray.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2) {
    result = 'claw.png';
  } else if (random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};

//iffy to populate the dice arrays on page load
(function populateDieArrays(){
  for(var die = 0; die < 4; die++){
    var orange = new Orange();
    var blue = new Blue();
    var gray = new Gray();

    orangeDiceArray.push(orange);
    blueDiceArray.push(blue);
    grayDiceArray.push(gray);
  }
})();

//does the initial roll for a round.
function startRound(){
  var dieTitleContainer = document.getElementById('Die-Title');
  for(var die = 0; die < 4; die++){
    orangeDiceArray[die].roll();
    blueDiceArray[die].roll();
    grayDiceArray[die].roll();
  }
  if(dieTitleContainer.children[1]){
    dieTitleContainer.removeChild(dieTitleContainer.children[1]);
    document.getElementById('Keep-Rolling').disabled = false;
  }
  //call to render images to page
  renderDice();
  countMaul();
  renderScore();
}

//renders the dice pool
function renderDice(){
  var orangeWrapper = document.getElementById('orange-dice');
  var grayWrapper = document.getElementById('gray-dice');
  var blueWrapper = document.getElementById('blue-dice');

  orangeWrapper.innerHTML = null;
  grayWrapper.innerHTML = null;
  blueWrapper.innerHTML = null;

  for(var die = 0; die < 4; die++){
    var orangeDie = document.createElement('img');
    var grayDie = document.createElement('img');
    var blueDie = document.createElement('img');

    orangeDie.classList.add(orangeDiceArray[die].lastRoll.split('.')[0]);
    grayDie.classList.add(grayDiceArray[die].lastRoll.split('.')[0]);
    blueDie.classList.add(blueDiceArray[die].lastRoll.split('.')[0]);

    orangeDie.src = '../images/' + orangeDiceArray[die].lastRoll;
    grayDie.src = '../images/' + grayDiceArray[die].lastRoll;
    blueDie.src = '../images/' + blueDiceArray[die].lastRoll;

    orangeWrapper.appendChild(orangeDie);
    grayWrapper.appendChild(grayDie);
    blueWrapper.appendChild(blueDie);
  }
}

//function to determine if player has been mauled.
function countMaul() {
  var clawCounter = 0;
  for(var die = 0; die < 4; die++) {
    if(orangeDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
  }
  if(clawCounter >= maxMauls) {
    var maulMessage = document.createElement('p');
    maulMessage.textContent = 'You\'ve been mauled by Sasquatch. Click End Turn to continue.';
    document.getElementById('Die-Title').appendChild(maulMessage);
    document.getElementById('Keep-Rolling').disabled = true;
    mauledFlag = true;
  }
}

//function to count cameras
function countCamera(){
  var cameraCounter = 0;
  for(var die = 0; die < 4; die++){
    if(orangeDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
  }
  scoreArray.push(cameraCounter);
}

//Generating a total score from scoreArray
function checkScore(){
  totalScore = 0;
  for(var i = 0; i < scoreArray.length; i++){
    totalScore += scoreArray[i];
  }
}

//function to render the score status in status board
function renderScore(){
  var getStatusDiv = document.getElementById('Render-Zone');
  getStatusDiv.innerHTML = null;
  var roundsRemaining = (maxRounds - roundCount) - 1;
  checkScore();
  var postRounds = document.createElement('p');
  postRounds.textContent = 'You have ' + roundsRemaining + ' rounds left.';
  var postCurrentScore = document.createElement('p');
  postCurrentScore.textContent = 'Your current score is: ' + totalScore;
  var postScoreToWin = document.createElement('p');
  postScoreToWin.textContent = 'Score needed to win: ' + photosToWin;
  postCurrentScore.id = 'scoreText';
  getStatusDiv.appendChild(postRounds);
  getStatusDiv.appendChild(postCurrentScore);
  getStatusDiv.appendChild(postScoreToWin);
}

//function that handles Keep-Rolling event
function handleKeepRolling() {
  for (var die = 0; die < 4; die++) {
    if (orangeDiceArray[die].lastRoll === 'tracks.jpg') {
      orangeDiceArray[die].roll();
    }
    if (grayDiceArray[die].lastRoll === 'tracks.jpg') {
      grayDiceArray[die].roll();
    }
    if (blueDiceArray[die].lastRoll === 'tracks.jpg') {
      blueDiceArray[die].roll();
    }
  }
  renderDice();
  countMaul();
}

//function that handles difficulty Selection and Game Start
function handleDifficulty(event) {
  roundCount = 0;
  scoreArray = [];
  var getStatusDiv = document.getElementById('Render-Zone');
  var clearImageAnimation = document.getElementById('imageAnimation');
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  var difficultyChosen = document.getElementById('select-difficulty').value;
  getStatusDiv.innerHTML = null;
  clearImageAnimation.innerHTML = null;
  event.preventDefault();
  for (var i = 0; i < difficultyForm.length; i++) {
    difficultyForm[i].disabled = true;
    // console.log(difficultyForm[i]);
  }
  if (difficultyChosen === 'easy') {
    maxRounds = 3;
    photosToWin = 5;
  } else if (difficultyChosen === 'medium') {
    maxRounds = 3;
    photosToWin = 7;
  } else {
    maxRounds = 2;
    photosToWin = 7;
  }
  document.getElementById('Dice-And-Status').hidden = false;
  document.getElementById('End-Turn').disabled = false;
  document.getElementById('Keep-Rolling').disabled = false;
  startRound();
}

//function that handles End-Turn
function handleEndTurn(){
  roundCount++;
  if(mauledFlag !== true){
    countCamera();
    //call the status board render function.
  } else {
    scoreArray.push(0);
    mauledFlag = false;
  }
  // checkScore();
  renderScore();
  var winText = document.createElement('p');
  var outcomeGif = document.createElement('img');
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  var newGameObject = new ThisGame(updateUser.userName, totalScore, document.getElementById('select-difficulty').value);
  var loseText = document.createElement('p');
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  var newGameObject = new ThisGame(updateUser.userName, totalScore, document.getElementById('select-difficulty').value);

  if(roundCount < maxRounds && totalScore < photosToWin){
    startRound();
  } else if(totalScore >= photosToWin){
    document.getElementById('End-Turn').disabled = true;
    document.getElementById('Keep-Rolling').disabled = true;
    document.getElementById('scoreText').style.color = 'green';
    var winText = document.createElement('p');
    winText.textContent = 'Congratulations, you\'ve solved the mystery of Sasquatch!';
    document.getElementById('imageAnimation').appendChild(winText);
    outcomeGif.src = '../images/sasquatchGif.gif';
    document.getElementById('imageAnimation').appendChild(outcomeGif);
    for (var i = 0; i < difficultyForm.length; i++) {
      difficultyForm[i].disabled = false;
    }
    gameArray.push(newGameObject);
    localStorage.setItem('gameArray', JSON.stringify(gameArray));
  } else{
    document.getElementById('End-Turn').disabled = true;
    document.getElementById('Keep-Rolling').disabled = true;
    document.getElementById('scoreText').style.color = 'red';
    loseText.textContent = 'Sorry, you\'ve been mauled to death. Please seek medical attention and try again later!';
    document.getElementById('imageAnimation').appendChild(loseText);
    outcomeGif.src = '../images/sasquatchmaul.gif';
    document.getElementById('imageAnimation').appendChild(outcomeGif);
    for (var i = 0; i < difficultyForm.length; i++) {
      difficultyForm[i].disabled = false;
    }
    gameArray.push(newGameObject);
    localStorage.setItem('gameArray', JSON.stringify(gameArray));
  }
}

// Iffy to check local storage for game data
(function checkLocal() {
  if(localStorage.getItem('gameArray')) {
    console.log('Local storage exists for game array');
    var parsedGameArray = JSON.parse(localStorage.getItem('gameArray'));
    gameArray = parsedGameArray;
  } else {
    console.log('Local storage does not exist for game array');
  }
  if(localStorage.getItem('currentUser')) {
    console.log('Local storage exists for current user');
    var parsedUser = JSON.parse(localStorage.getItem('currentUser'));
    updateUser = parsedUser;
  } else {
    console.log('local storage does not exist for current user');
    alert('You must be logged in to play. Please create a username on our home page.');
    location.assign('stats.html');
  }
})();

//adds event listener to submit button to choose difficulty
document.getElementById('difficulty').addEventListener('submit', handleDifficulty);

//adds event listener to Keep-Rolling button
document.getElementById('Keep-Rolling').addEventListener('click', handleKeepRolling);

//adds event listener to End-Turn button
document.getElementById('End-Turn').addEventListener('click', handleEndTurn);
<commit_msg>Grouping the iffys in the game code, fixing a couple of bugs with the re-direct and round counting.<commit_after>'use strict';

//Dice type arrays
var orangeDiceArray = [];
var blueDiceArray = [];
var grayDiceArray = [];
var maxRounds = 0;
var roundCount = 0;
var maxMauls = 5;
var photosToWin = 0;
var mauledFlag = false;
var scoreArray = [];
var gameArray = [];
var totalScore = 0;
var updateUser = new User();

function ThisGame(userName, score, difficulty) {
  this.userName = userName;
  this.score = score;
  this.difficulty = difficulty;
}

function User() {
  this.userName = '';
}

//Generic die constructor
function Die(maul, photo, footprint) {
  this.maul = maul;
  this.photo = photo;
  this.footprint = footprint;
  this.lastRoll = '';
}

//Method for generating random number
Die.prototype.randomNumber = function() {
  var baseNumber = Math.floor(Math.random() * (6) + 1);
  return baseNumber;
};

//Orange die constructor (hardest)
function Orange() {}
Orange.prototype = new Die(3,1,2);

//Blue die constructor (easiest)
function Blue() {}
Blue.prototype = new Die(1,3,2);

//Gray die constructor (medium)
function Gray() {}
Gray.prototype = new Die(2,2,2);

//Roll method for the orange dice
Orange.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2 || random === 3) {
    result = 'claw.png';
  } else if (random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};

//Roll method for the blue dice
Blue.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1) {
    result = 'claw.png';
  } else if (random === 2 || random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};

//Roll method for the gray dice
Gray.prototype.roll = function() {
  var random = this.randomNumber();
  var result = '';
  console.log(random);
  if (random === 1 || random === 2) {
    result = 'claw.png';
  } else if (random === 3 || random === 4) {
    result = 'camera.png';
  } else {
    result = 'tracks.jpg';
  }
  this.lastRoll = result;
};

// Iffy to check local storage for game data
(function checkLocal() {
  if(localStorage.getItem('gameArray')) {
    console.log('Local storage exists for game array');
    var parsedGameArray = JSON.parse(localStorage.getItem('gameArray'));
    gameArray = parsedGameArray;
  } else {
    console.log('Local storage does not exist for game array');
  }
  if(localStorage.getItem('currentUser')) {
    console.log('Local storage exists for current user');
    var parsedUser = JSON.parse(localStorage.getItem('currentUser'));
    updateUser = parsedUser;
  } else {
    console.log('local storage does not exist for current user');
    alert('You must be logged in to play. Please create a username or login, redirecting you to the Dashboard page.');
    location.assign('../index.html');
  }
})();

//iffy to populate the dice arrays on page load
(function populateDieArrays(){
  for(var die = 0; die < 4; die++){
    var orange = new Orange();
    var blue = new Blue();
    var gray = new Gray();

    orangeDiceArray.push(orange);
    blueDiceArray.push(blue);
    grayDiceArray.push(gray);
  }
})();

//does the initial roll for a round.
function startRound(){
  var dieTitleContainer = document.getElementById('Die-Title');
  for(var die = 0; die < 4; die++){
    orangeDiceArray[die].roll();
    blueDiceArray[die].roll();
    grayDiceArray[die].roll();
  }
  if(dieTitleContainer.children[1]){
    dieTitleContainer.removeChild(dieTitleContainer.children[1]);
    document.getElementById('Keep-Rolling').disabled = false;
  }
  renderDice();
  countMaul();
  renderScore();
}

//renders the dice pool
function renderDice(){
  var orangeWrapper = document.getElementById('orange-dice');
  var grayWrapper = document.getElementById('gray-dice');
  var blueWrapper = document.getElementById('blue-dice');

  orangeWrapper.innerHTML = null;
  grayWrapper.innerHTML = null;
  blueWrapper.innerHTML = null;

  for(var die = 0; die < 4; die++){
    var orangeDie = document.createElement('img');
    var grayDie = document.createElement('img');
    var blueDie = document.createElement('img');

    orangeDie.classList.add(orangeDiceArray[die].lastRoll.split('.')[0]);
    grayDie.classList.add(grayDiceArray[die].lastRoll.split('.')[0]);
    blueDie.classList.add(blueDiceArray[die].lastRoll.split('.')[0]);

    orangeDie.src = '../images/' + orangeDiceArray[die].lastRoll;
    grayDie.src = '../images/' + grayDiceArray[die].lastRoll;
    blueDie.src = '../images/' + blueDiceArray[die].lastRoll;

    orangeWrapper.appendChild(orangeDie);
    grayWrapper.appendChild(grayDie);
    blueWrapper.appendChild(blueDie);
  }
}

//function to determine if player has been mauled.
function countMaul() {
  var clawCounter = 0;
  for(var die = 0; die < 4; die++) {
    if(orangeDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'claw.png') {
      clawCounter++;
    }
  }
  if(clawCounter >= maxMauls) {
    var maulMessage = document.createElement('p');
    maulMessage.textContent = 'You\'ve been mauled by Sasquatch. Click End Turn to continue.';
    document.getElementById('Die-Title').appendChild(maulMessage);
    document.getElementById('Keep-Rolling').disabled = true;
    mauledFlag = true;
  }
}

//function to count cameras
function countCamera(){
  var cameraCounter = 0;
  for(var die = 0; die < 4; die++){
    if(orangeDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
    if(grayDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
    if(blueDiceArray[die].lastRoll === 'camera.png'){
      cameraCounter++;
    }
  }
  scoreArray.push(cameraCounter);
}

//Generating a total score from scoreArray
function checkScore(){
  totalScore = 0;
  for(var i = 0; i < scoreArray.length; i++){
    totalScore += scoreArray[i];
  }
}

//function to render the score status in status board
function renderScore(){
  var getStatusDiv = document.getElementById('Render-Zone');
  var roundsRemaining = maxRounds - roundCount;
  var postRounds = document.createElement('p');
  var postCurrentScore = document.createElement('p');
  var postScoreToWin = document.createElement('p');

  getStatusDiv.innerHTML = null;
  checkScore();
  postRounds.textContent = 'You have ' + roundsRemaining + ' rounds left.';
  postCurrentScore.textContent = 'Your current score is: ' + totalScore;
  postScoreToWin.textContent = 'Score needed to win: ' + photosToWin;
  postCurrentScore.id = 'scoreText';
  getStatusDiv.appendChild(postRounds);
  getStatusDiv.appendChild(postCurrentScore);
  getStatusDiv.appendChild(postScoreToWin);
}

//function that handles Keep-Rolling event
function handleKeepRolling() {
  for (var die = 0; die < 4; die++) {
    if (orangeDiceArray[die].lastRoll === 'tracks.jpg') {
      orangeDiceArray[die].roll();
    }
    if (grayDiceArray[die].lastRoll === 'tracks.jpg') {
      grayDiceArray[die].roll();
    }
    if (blueDiceArray[die].lastRoll === 'tracks.jpg') {
      blueDiceArray[die].roll();
    }
  }
  renderDice();
  countMaul();
}

//function that handles difficulty Selection and Game Start
function handleDifficulty(event) {
  roundCount = 1;
  scoreArray = [];
  var getStatusDiv = document.getElementById('Render-Zone');
  var clearImageAnimation = document.getElementById('imageAnimation');
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  var difficultyChosen = document.getElementById('select-difficulty').value;
  getStatusDiv.innerHTML = null;
  clearImageAnimation.innerHTML = null;
  event.preventDefault();
  for (var i = 0; i < difficultyForm.length; i++) {
    difficultyForm[i].disabled = true;
  }
  if (difficultyChosen === 'easy') {
    maxRounds = 3;
    photosToWin = 5;
  } else if (difficultyChosen === 'medium') {
    maxRounds = 3;
    photosToWin = 7;
  } else {
    maxRounds = 2;
    photosToWin = 7;
  }
  document.getElementById('Dice-And-Status').hidden = false;
  document.getElementById('End-Turn').disabled = false;
  document.getElementById('Keep-Rolling').disabled = false;
  startRound();
}

//function that handles End-Turn
function handleEndTurn(){
  roundCount++;
  if(mauledFlag !== true){
    countCamera();
  } else {
    scoreArray.push(0);
    mauledFlag = false;
  }
  renderScore();
  var winText = document.createElement('p');
  var outcomeGif = document.createElement('img');
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  var newGameObject = new ThisGame(updateUser.userName, totalScore, document.getElementById('select-difficulty').value);
  var loseText = document.createElement('p');
  var difficultyForm = document.getElementsByClassName('difficulty-submission');
  var newGameObject = new ThisGame(updateUser.userName, totalScore, document.getElementById('select-difficulty').value);

  if(roundCount < maxRounds && totalScore < photosToWin){
    startRound();
  } else if(totalScore >= photosToWin){
    document.getElementById('End-Turn').disabled = true;
    document.getElementById('Keep-Rolling').disabled = true;
    document.getElementById('scoreText').style.color = 'green';
    var winText = document.createElement('p');
    winText.textContent = 'Congratulations, you\'ve solved the mystery of Sasquatch!';
    document.getElementById('imageAnimation').appendChild(winText);
    outcomeGif.src = '../images/sasquatchGif.gif';
    document.getElementById('imageAnimation').appendChild(outcomeGif);
    for (var i = 0; i < difficultyForm.length; i++) {
      difficultyForm[i].disabled = false;
    }
    gameArray.push(newGameObject);
    localStorage.setItem('gameArray', JSON.stringify(gameArray));
  } else{
    document.getElementById('End-Turn').disabled = true;
    document.getElementById('Keep-Rolling').disabled = true;
    document.getElementById('scoreText').style.color = 'red';
    loseText.textContent = 'Sorry, you\'ve been mauled to death. Please seek medical attention and try again later!';
    document.getElementById('imageAnimation').appendChild(loseText);
    outcomeGif.src = '../images/sasquatchmaul.gif';
    document.getElementById('imageAnimation').appendChild(outcomeGif);
    for (var i = 0; i < difficultyForm.length; i++) {
      difficultyForm[i].disabled = false;
    }
    gameArray.push(newGameObject);
    localStorage.setItem('gameArray', JSON.stringify(gameArray));
  }
}

//adds event listener to submit button to choose difficulty
document.getElementById('difficulty').addEventListener('submit', handleDifficulty);

//adds event listener to Keep-Rolling button
document.getElementById('Keep-Rolling').addEventListener('click', handleKeepRolling);

//adds event listener to End-Turn button
document.getElementById('End-Turn').addEventListener('click', handleEndTurn);
<|endoftext|>


<commit_before>
/* Game namespace */
var game = {

    // an object where to store game information
    data : { },

    // Run on page load.
    onload : function () {
        // Initialize the video.
        var scale = 3 * window.devicePixelRatio;
        if (!me.video.init(160, 144, { wrapper : 'screen', scale : scale })) {
            alert('Your browser does not support HTML5 canvas.');
            return;
        }

        // Initialize the audio.
        me.audio.init('mp3,ogg');

        // setting up sound
        me.audio.samplePlaying = null;
        me.audio.samplePriority.action = ['kick', 'jump'];
        me.audio.playUnique = function(soundName, channel, loop) {
            // set to default channel
            channel = channel || 'default';

            // get samples priority
            var selfId = me.audio.samplePriority[channel].indexOf(soundName);
            var currentId = me.audio.samplePriority[channel].indexOf(me.audio.samplePlaying);

            // if this sample is in the priority list
            if (selfId >= 0) {
                // if a sound is playing,
                if (currentId >= 0) {
                    // if has a lower priority
                    if (selfId < currentId) {
                        // we stop current sample only
                        me.audio.stop(me.audio.samplePlaying);
                        me.audio.samplePlaying = null;
                    } else {
                        // we do nothing
                        return null;
                    }
                }

                // we play a sound
                me.audio.samplePlaying = soundName;
                return me.audio.play(soundName, loop, function () {
                    me.audio.samplePlaying = null;
                });
            } else {
                return null;
            }
        }

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    loaded : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());

        // add our player entity in the entity pool
        me.pool.register('player', game.PlayerEntity);
        me.pool.register('ball', game.BallEntity);
        me.pool.register('piglet', game.PigletEntity);
        me.pool.register('boar', game.BoarEntity);

        // enable the keyboard
        me.input.bindKey(me.input.KEY.LEFT, 'left');
        me.input.bindKey(me.input.KEY.RIGHT, 'right');
        me.input.bindKey(me.input.KEY.UP, 'jump', true);
        me.input.bindKey(me.input.KEY.A, 'kick', true);
        // added for debug purposes
        me.input.bindKey(me.input.KEY.E, 'debug', true);

        // sets global gravity
        me.sys.gravity = 0.7;

        // starts the game.
        me.state.change(me.state.PLAY);
    }
};
<commit_msg>Audio fix<commit_after>
/* Game namespace */
var game = {

    // an object where to store game information
    data : { },

    // Run on page load.
    onload : function () {
        // Initialize the video.
        var scale = 3 * window.devicePixelRatio;
        if (!me.video.init(160, 144, { wrapper : 'screen', scale : scale })) {
            alert('Your browser does not support HTML5 canvas.');
            return;
        }

        // Initialize the audio.
        me.audio.init('mp3,ogg');

        // setting up sound
        me.audio.samplePlaying = null;
        me.audio.samplePriority = {
            action: ['kick', 'jump']
        };
        me.audio.playUnique = function(soundName, channel, loop) {
            // set to default channel
            channel = channel || 'default';

            // get samples priority
            var selfId = me.audio.samplePriority[channel].indexOf(soundName);
            var currentId = me.audio.samplePriority[channel].indexOf(me.audio.samplePlaying);

            // if this sample is in the priority list
            if (selfId >= 0) {
                // if a sound is playing,
                if (currentId >= 0) {
                    // if has a lower priority
                    if (selfId < currentId) {
                        // we stop current sample only
                        me.audio.stop(me.audio.samplePlaying);
                        me.audio.samplePlaying = null;
                    } else {
                        // we do nothing
                        return null;
                    }
                }

                // we play a sound
                me.audio.samplePlaying = soundName;
                return me.audio.play(soundName, loop, function () {
                    me.audio.samplePlaying = null;
                });
            } else {
                return null;
            }
        }

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    loaded : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());

        // add our player entity in the entity pool
        me.pool.register('player', game.PlayerEntity);
        me.pool.register('ball', game.BallEntity);
        me.pool.register('piglet', game.PigletEntity);
        me.pool.register('boar', game.BoarEntity);

        // enable the keyboard
        me.input.bindKey(me.input.KEY.LEFT, 'left');
        me.input.bindKey(me.input.KEY.RIGHT, 'right');
        me.input.bindKey(me.input.KEY.UP, 'jump', true);
        me.input.bindKey(me.input.KEY.A, 'kick', true);
        // added for debug purposes
        me.input.bindKey(me.input.KEY.E, 'debug', true);

        // sets global gravity
        me.sys.gravity = 0.7;

        // starts the game.
        me.state.change(me.state.PLAY);
    }
};
<|endoftext|>


<commit_before>define(["lodash", "backbone", "jquery", "js/enum", "js/views/header", "js/models/dataAccessor"],
    function(_, Backbone, $, Enum, HeaderView, DataAccessor) {
        var game = {
                eventsBus: _.extend({}, Backbone.Events),
                db: null,
                router: null,
                status: Enum.GameStatus.LOADING,
                initializeDfd: new $.Deferred()
            };

        _.extend(game, {
            VERSION: "0.2",

            initialize: function (router) {
                var header = new HeaderView({ el: $("#header").get(0) });

                this.router = router;

                this.printVersionInfo();

                header.render();

                if (!this.checkBrowser()) {
                    return router.navigate("error/" + Enum.GameErrorTypes.OLD_BROWSER, { trigger: true });
                }

                this.eventsBus.on("header.toggleInstructions", _.bind(header.toggleInstructions, header));

                this.db = new DataAccessor({ encrypter: CryptoJS });
                this.initializeDB()
                    .done(function () {
                        game.status = Enum.GameStatus.READY;
                        game.initializeUser().then(function (user) {
                            game.db.saveCurrentUserName(user.get("name"));
                            game.eventsBus.trigger("levels.loaded");
                            game.initializeDfd.resolve();
                        });
                    })
                    .fail(function () {
                        return router.navigate("error/" + Enum.GameErrorTypes.NO_LEVELS_LOADED, { trigger: true });
                    });
            },

            onInitialize: function (callback) {
                $.when(this.initializeDfd).done(callback);
            },

            printVersionInfo: function () {
                var log = console && console.log || function () {};
                log.call(console, "===========================");
                log.call(console, "= Backbone: " + Backbone.VERSION);
                log.call(console, "= Lodash: " + _.VERSION);
                log.call(console, "= jQuery: " + $.fn.jquery);
                log.call(console, "= Link It: " + this.VERSION);
                log.call(console, "===========================");
            },

            checkBrowser: function () {
                return !! (window.indexedDB && window.localStorage);
            },

            initializeDB: function () {
                return this.db.initDB()
                    .then(function () {
                        if (game.db.getLevelsCount() < 1) {
                            //no levels - let's try to load them!
                            return game.db.fetchLevels().then(function () {
                                game.eventsBus.trigger("levels.loaded");
                            });
                        }
                    });
            },

            initializeUser: function () {
                return this.db.initUser(this.db.getCurrentUserName());
            },

            navigateToLevel: function (levelNum) {
                var router = this.router,
                    db = this.db;

                return this.db.getCurrentUserActiveLevel().then(function (activeLevel) {
                    if (levelNum <= activeLevel) {
                        router.hideCurrentView();
                        if (db.getLevelsCount() >= levelNum) {
                            router.navigate("level/" + levelNum);
                            return router.showLevelView(levelNum);
                        } else {
                            return router.navigate("gameOver");
                        }
                    } else {
                        return router.navigate("error/" + Enum.GameErrorTypes.PAGE_NOT_FOUND, { trigger: true });
                    }
                }, function (e) {
                    return router.navigate("error/" + Enum.GameErrorTypes.USER_ERROR, { trigger: true });
                });
            },

            updateActiveLevel: function (passedLevelIndex) {
                var db = this.db;

                return db.getCurrentUserActiveLevel().then(function (activeLevel) {
                    if (activeLevel === passedLevelIndex) {
                        return db.setCurrentUserActiveLevel(passedLevelIndex + 1);
                    } else {
                        return passedLevelIndex + 1;
                    }
                });
            }

        });

        return game;
});<commit_msg>Fix Game Over view navigation;<commit_after>define(["lodash", "backbone", "jquery", "js/enum", "js/views/header", "js/models/dataAccessor"],
    function(_, Backbone, $, Enum, HeaderView, DataAccessor) {
        var game = {
                eventsBus: _.extend({}, Backbone.Events),
                db: null,
                router: null,
                status: Enum.GameStatus.LOADING,
                initializeDfd: new $.Deferred()
            };

        _.extend(game, {
            VERSION: "0.2",

            initialize: function (router) {
                var header = new HeaderView({ el: $("#header").get(0) });

                this.router = router;

                this.printVersionInfo();

                header.render();

                if (!this.checkBrowser()) {
                    return router.navigate("error/" + Enum.GameErrorTypes.OLD_BROWSER, { trigger: true });
                }

                this.eventsBus.on("header.toggleInstructions", _.bind(header.toggleInstructions, header));

                this.db = new DataAccessor({ encrypter: CryptoJS });
                this.initializeDB()
                    .done(function () {
                        game.status = Enum.GameStatus.READY;
                        game.initializeUser().then(function (user) {
                            game.db.saveCurrentUserName(user.get("name"));
                            game.eventsBus.trigger("levels.loaded");
                            game.initializeDfd.resolve();
                        });
                    })
                    .fail(function () {
                        return router.navigate("error/" + Enum.GameErrorTypes.NO_LEVELS_LOADED, { trigger: true });
                    });
            },

            onInitialize: function (callback) {
                $.when(this.initializeDfd).done(callback);
            },

            printVersionInfo: function () {
                var log = console && console.log || function () {};
                log.call(console, "===========================");
                log.call(console, "= Backbone: " + Backbone.VERSION);
                log.call(console, "= Lodash: " + _.VERSION);
                log.call(console, "= jQuery: " + $.fn.jquery);
                log.call(console, "= Link It: " + this.VERSION);
                log.call(console, "===========================");
            },

            checkBrowser: function () {
                return !! (window.indexedDB && window.localStorage);
            },

            initializeDB: function () {
                return this.db.initDB()
                    .then(function () {
                        if (game.db.getLevelsCount() < 1) {
                            //no levels - let's try to load them!
                            return game.db.fetchLevels().then(function () {
                                game.eventsBus.trigger("levels.loaded");
                            });
                        }
                    });
            },

            initializeUser: function () {
                return this.db.initUser(this.db.getCurrentUserName());
            },

            navigateToLevel: function (levelNum) {
                var router = this.router,
                    db = this.db;

                return this.db.getCurrentUserActiveLevel().then(function (activeLevel) {
                    if (levelNum <= activeLevel) {
                        if (db.getLevelsCount() >= levelNum) {
                            router.navigate("level/" + levelNum);
                            router.hideCurrentView();
                            return router.showLevelView(levelNum);
                        } else {
                            return router.navigate("gameOver", { trigger: true });
                        }
                    } else {
                        return router.navigate("error/" + Enum.GameErrorTypes.PAGE_NOT_FOUND, { trigger: true });
                    }
                }, function (e) {
                    return router.navigate("error/" + Enum.GameErrorTypes.USER_ERROR, { trigger: true });
                });
            },

            updateActiveLevel: function (passedLevelIndex) {
                var db = this.db;

                return db.getCurrentUserActiveLevel().then(function (activeLevel) {
                    if (activeLevel === passedLevelIndex) {
                        return db.setCurrentUserActiveLevel(passedLevelIndex + 1);
                    } else {
                        return passedLevelIndex + 1;
                    }
                });
            }

        });

        return game;
});<|endoftext|>


<commit_before>function Game(song) {
	this.controls = globals.controls;
	this.score = 0;
	var example_song = document.getElementById('example_song');
	example_song.play();
	this.startTime = this.currentTime();
	this.song = song;
	this.graphics = new Graphics(this);
	this.timeToShow =  this.graphics.LENGTH_TO_LINE / this.NOTE_SPEED;
	this.pressedNotes = new Array();
	// Initialize array to avoid errors
	for (var i = 0; i < 5; i++) {
		this.pressedNotes[i] = new Note(0, 0, 0);
	}
	var nextNote = 0;
	//this.graphics.init_scene();
	this.lastUpdateTime = 0;
	this.lastScore = 0;

}

Game.prototype = {
	NOTE_SPEED: 0.004, // 0.004 units/ms
	NOTE_ACCURACY: 150, // 300ms accuracy required for the player to hit the notes

	show_note: function(note) {
		var timeDiff = note.start - this.timeFromStart();
		//note.mesh.translateOnAxis(this.graphics.neckDir, timeDiff * this.NOTE_SPEED);

		var vecDelta = this.graphics.neckDir.clone();
		vecDelta.multiplyScalar(timeDiff * this.NOTE_SPEED);
		note.head_mesh.position.add(vecDelta);
		note.mesh.position.add(vecDelta);

		this.graphics.scene.add(note.mesh);
		this.graphics.scene.add(note.head_mesh);
		//this.graphics.notes.push(note);
	},

	set_note_positions: function(timeFromStart) {
		for (var i = this.song.notes.lastShownIndex; i > this.song.notes.lastDisappearedIndex; i--) {
			var note = this.song.notes[i];
			this.set_note_position(note, timeFromStart);
		}
	},

	set_note_position: function(note, timeFromStart) {
		var buffer = 1000; // Wait 1 sec before removing the note to make sure it's already out of view
		var endTimeDiff = note.end - timeFromStart;
		if (endTimeDiff < 0 - buffer) {
			this.graphics.scene.remove(note.mesh);
			this.graphics.scene.remove(note.head_mesh);
			if (endTimeDiff < 5000) {
				this.song.notes.lastDisappearedIndex = this.song.notes.indexOf(note); // TODO: really define the last disappeared note
			}
		}

		var timeDiff = note.start - timeFromStart;

		var pos = this.graphics.NOTES_POS_0.clone();
		pos.add(this.graphics.NOTES_POS_DELTA.clone().multiplyScalar(note.label));

		var vecDelta = this.graphics.neckDir.clone();
		vecDelta.multiplyScalar(timeDiff * this.NOTE_SPEED);

		pos.add(vecDelta);
		note.mesh.position = pos;
		note.head_mesh.position = pos;
	},

	currentTime: function() {
		var d = new Date();
		return d.getTime();
	},

	timeFromStart: function() {
		var currTime = this.currentTime();
		return currTime - this.startTime;
	},

	stopNote: function(label) {
		if (this.pressedNotes[label].isPressed) {
			this.pressedNotes[label].isPressed = false;
			this.pressedNotes[label].mesh.material = globals.game.graphics.get_note_material(label, false);
			this.pressedNotes[label].head_mesh.material = globals.game.graphics.get_note_material(label, false);
			globals.game.graphics.pointLights[label].visible = false;
		}
	},

	update: function() {
		var timeFromStart = this.timeFromStart();

		if (timeFromStart / 1000 > document.getElementById('example_song').duration) {
			/**
			*	The song has ended
			*/
			cancelAnimationFrame(animate);
			window.location = "../highscore?a=" + globals.game.score.toString();
		}

		if (timeFromStart / 1000 > 20) {
			sessionStorage.score = globals.game.score.toString();
			window.location = "../highscore";
		}

		this.updateScores(timeFromStart);
		this.lastUpdateTime = timeFromStart;

		this.getNotesToShow();
		this.stopNotes(timeFromStart);
		//this.set_note_positions(timeFromStart);
	},

	stopNotes: function(timeFromStart) {
		for (var i = 0; i < this.pressedNotes.length; i++) {
			var note = this.pressedNotes[i];
			if (note.end <= timeFromStart && note.isPressed) {
				this.stopNote(i);
			}
		}
	},

	updateScores: function(timeFromStart) {
		for (var i = 0; i < this.pressedNotes.length; i++) {
			if (this.pressedNotes[i].isPressed) {
				var afterEnd = Math.max(0, timeFromStart - Math.round(this.pressedNotes[i].end));
				var afterLastUpdate = Math.max(0, timeFromStart - this.lastUpdateTime);
				var beforeStart = Math.max(0, Math.min(Math.round(this.pressedNotes[i].start)
					 - this.lastUpdateTime, afterLastUpdate));
				this.score += afterLastUpdate - afterEnd - beforeStart;
			}
		}
		//if (Math.floor(this.lastScore / 20) < Math.floor(this.score / 20)) {
			this.graphics.setScores(this.score);
		//}
		this.lastScore = this.score;
	},

	getNotesToShow: function() {
			var i = this.song.notes.lastShownIndex + 1;
			var bufferTime = 300;
			while (i < this.song.notes.length) {
				var note = this.song.notes[i];
				var timeToNote = note.start - this.timeFromStart();
				if (timeToNote > this.timeToShow - bufferTime) break;
				i++;
			}
			// Push all the notes to be shown to the renderer's list and show them
			for (var j = this.song.notes.lastShownIndex + 1; j < i; j++) {
				var note = this.song.notes[j];
				this.show_note(note);
			}
			this.song.notes.lastShownIndex = i-1;
		}
}
<commit_msg>Fixed ending time<commit_after>function Game(song) {
	this.controls = globals.controls;
	this.score = 0;
	var example_song = document.getElementById('example_song');
	example_song.play();
	this.startTime = this.currentTime();
	this.song = song;
	this.graphics = new Graphics(this);
	this.timeToShow =  this.graphics.LENGTH_TO_LINE / this.NOTE_SPEED;
	this.pressedNotes = new Array();
	// Initialize array to avoid errors
	for (var i = 0; i < 5; i++) {
		this.pressedNotes[i] = new Note(0, 0, 0);
	}
	var nextNote = 0;
	//this.graphics.init_scene();
	this.lastUpdateTime = 0;
	this.lastScore = 0;

}

Game.prototype = {
	NOTE_SPEED: 0.004, // 0.004 units/ms
	NOTE_ACCURACY: 150, // 300ms accuracy required for the player to hit the notes

	show_note: function(note) {
		var timeDiff = note.start - this.timeFromStart();
		//note.mesh.translateOnAxis(this.graphics.neckDir, timeDiff * this.NOTE_SPEED);

		var vecDelta = this.graphics.neckDir.clone();
		vecDelta.multiplyScalar(timeDiff * this.NOTE_SPEED);
		note.head_mesh.position.add(vecDelta);
		note.mesh.position.add(vecDelta);

		this.graphics.scene.add(note.mesh);
		this.graphics.scene.add(note.head_mesh);
		//this.graphics.notes.push(note);
	},

	set_note_positions: function(timeFromStart) {
		for (var i = this.song.notes.lastShownIndex; i > this.song.notes.lastDisappearedIndex; i--) {
			var note = this.song.notes[i];
			this.set_note_position(note, timeFromStart);
		}
	},

	set_note_position: function(note, timeFromStart) {
		var buffer = 1000; // Wait 1 sec before removing the note to make sure it's already out of view
		var endTimeDiff = note.end - timeFromStart;
		if (endTimeDiff < 0 - buffer) {
			this.graphics.scene.remove(note.mesh);
			this.graphics.scene.remove(note.head_mesh);
			if (endTimeDiff < 5000) {
				this.song.notes.lastDisappearedIndex = this.song.notes.indexOf(note); // TODO: really define the last disappeared note
			}
		}

		var timeDiff = note.start - timeFromStart;

		var pos = this.graphics.NOTES_POS_0.clone();
		pos.add(this.graphics.NOTES_POS_DELTA.clone().multiplyScalar(note.label));

		var vecDelta = this.graphics.neckDir.clone();
		vecDelta.multiplyScalar(timeDiff * this.NOTE_SPEED);

		pos.add(vecDelta);
		note.mesh.position = pos;
		note.head_mesh.position = pos;
	},

	currentTime: function() {
		var d = new Date();
		return d.getTime();
	},

	timeFromStart: function() {
		var currTime = this.currentTime();
		return currTime - this.startTime;
	},

	stopNote: function(label) {
		if (this.pressedNotes[label].isPressed) {
			this.pressedNotes[label].isPressed = false;
			this.pressedNotes[label].mesh.material = globals.game.graphics.get_note_material(label, false);
			this.pressedNotes[label].head_mesh.material = globals.game.graphics.get_note_material(label, false);
			globals.game.graphics.pointLights[label].visible = false;
		}
	},

	update: function() {
		var timeFromStart = this.timeFromStart();

		if (timeFromStart / 1000 > document.getElementById('example_song').duration) {
			/**
			*	The song has ended
			*/
			cancelAnimationFrame(animate);
			sessionStorage.score = globals.game.score.toString();
			window.location = "../highscore";
		}

		this.updateScores(timeFromStart);
		this.lastUpdateTime = timeFromStart;

		this.getNotesToShow();
		this.stopNotes(timeFromStart);
		//this.set_note_positions(timeFromStart);
	},

	stopNotes: function(timeFromStart) {
		for (var i = 0; i < this.pressedNotes.length; i++) {
			var note = this.pressedNotes[i];
			if (note.end <= timeFromStart && note.isPressed) {
				this.stopNote(i);
			}
		}
	},

	updateScores: function(timeFromStart) {
		for (var i = 0; i < this.pressedNotes.length; i++) {
			if (this.pressedNotes[i].isPressed) {
				var afterEnd = Math.max(0, timeFromStart - Math.round(this.pressedNotes[i].end));
				var afterLastUpdate = Math.max(0, timeFromStart - this.lastUpdateTime);
				var beforeStart = Math.max(0, Math.min(Math.round(this.pressedNotes[i].start)
					 - this.lastUpdateTime, afterLastUpdate));
				this.score += afterLastUpdate - afterEnd - beforeStart;
			}
		}
		//if (Math.floor(this.lastScore / 20) < Math.floor(this.score / 20)) {
			this.graphics.setScores(this.score);
		//}
		this.lastScore = this.score;
	},

	getNotesToShow: function() {
			var i = this.song.notes.lastShownIndex + 1;
			var bufferTime = 300;
			while (i < this.song.notes.length) {
				var note = this.song.notes[i];
				var timeToNote = note.start - this.timeFromStart();
				if (timeToNote > this.timeToShow - bufferTime) break;
				i++;
			}
			// Push all the notes to be shown to the renderer's list and show them
			for (var j = this.song.notes.lastShownIndex + 1; j < i; j++) {
				var note = this.song.notes[j];
				this.show_note(note);
			}
			this.song.notes.lastShownIndex = i-1;
		}
}
<|endoftext|>


<commit_before>var Cell = require('./cell'),
    Distance = require('./distance'),
    rand = require('./rand');

function Grid(rows, cols) {
  this.grid = [];
  for (var r = 0; r < rows; r++) {
    this.grid.push([]);
    for (var c = 0; c < cols; c++) {
      this.grid[r].push(new Cell(r, c));
    }
  }
}

Grid.prototype.eachRow = function () {
  var rows = [];
  for (var r = 0, rlen = this.grid.length; r < rlen; r++) {
    rows.push(this.grid[r]);
  }
  return rows;
};

Grid.prototype.eachCell = function () {
  var cells = [];
  for (var r = 0, rlen = this.grid.length; r < rlen; r++) {
    for (var c = 0, clen = this.grid[r].length; c < clen; c++) {
      cells.push(this.grid[r][c]);
    }
  }
  return cells;
};

Grid.prototype.northOf = function (cell) {
  var r = cell.getRow() - 1;
  if (r < 0) {
    return null;
  }
  return this.grid[r][cell.getCol()];
};

Grid.prototype.eastOf = function (cell) {
  var r = cell.getRow(),
      c = cell.getCol() + 1;
  if (c >= this.grid[r].length) {
    return null;
  }
  return this.grid[r][c];
};

Grid.prototype.southOf = function (cell) {
  var r = cell.getRow() + 1;
  if (r >= this.grid.length) {
    return null;
  }
  return this.grid[r][cell.getCol()];
};

Grid.prototype.westOf = function (cell) {
  var c = cell.getCol() - 1;
  if (c < 0) {
    return null;
  }
  return this.grid[cell.getRow()][c];
};

Grid.prototype.neighborsOf = function (cell) {
  var neighbors = [],
      north = this.northOf(cell),
      east = this.eastOf(cell),
      south = this.southOf(cell),
      west = this.westOf(cell);
  if (!!north) neighbors.push(north);
  if (!!east) neighbors.push(east);
  if (!!south) neighbors.push(south);
  if (!!west) neighbors.push(west);
  return neighbors;
};

Grid.prototype.randomCell = function () {
  var r = rand(this.grid.length),
      c = rand(this.grid[0].length);
  return this.grid[r][c];
};

Grid.prototype.distances = function (r, c) {
  var root = this.grid[r||0][c||0],
      distances = new Distance(root),
      frontier = [root];
  while (frontier.length !== 0) {
    var newFrontier = [];
    frontier.forEach(function (cell) {
      cell.links.forEach(function (linked) {
        if (typeof distances.get(linked) === 'number') return;
        distances.set(linked, distances.get(cell)+1);
        newFrontier.push(linked);
      });
    });
    frontier = newFrontier;
  }
  return distances;
};

Grid.prototype.toString = function (contentOf) {
  function body(cell) {
    if (!contentOf) return '   ';
    var content = contentOf(cell);
    if (typeof content !== 'number') return '   ';
    else if (content <  10) return '  '+ content;
    else if (content < 100) return ' ' + content;
    return content;
  }
  var output = '';
  var cols = this.grid[0].length;

  output += '+';
  for (var i = 0; i < cols; i++)
    output += '---+';
  output += '\n';

  for (var r = 0, rlen = this.grid.length; r < rlen; r++) {
    var row = this.grid[r];
    var top = '|', bottom = '+';
    for (var c = 0, clen = row.length; c < clen; c++) {
      var cell = row[c];
      var eastBoundary = cell.isLinked(this.eastOf(cell)) ? ' ' : '|';
      var southBoundary = cell.isLinked(this.southOf(cell)) ? '   ' : '---';
      var corner = '+';
      top += body(cell) + eastBoundary;
      bottom += southBoundary + corner;
    }
    output += top +'\n';
    output += bottom + '\n';
  }
  return output;
};

Grid.prototype.draw = function (param) {
  if (!param.canvasId)
    throw new 'requires canvasId';
  var canvasId = param.canvasId,
      cellSize = param.cellSize || 10;

  var self = this,
      canvas = document.getElementById(canvasId),
      g = canvas.getContext("2d"),
      drawLine = function (x1, y1, x2, y2, color) {
        g.strokeStyle = color || 'black';
        g.beginPath();
        g.moveTo(x1, y1);
        g.lineTo(x2, y2);
        g.lineWidth = 1;
        g.stroke();
      };

  canvas.width = cellSize * this.grid[0].length + 1;
  canvas.height = cellSize * this.grid.length + 1;

  g.translate(0.5, 0.5);
  g.font = '12px "sans serif"';
  g.textAlign = 'center';

  this.eachCell().forEach(function (cell) {
    var x1 = cell.col * cellSize,
        y1 = cell.row * cellSize,
        x2 = (cell.col + 1) * cellSize,
        y2 = (cell.row + 1) * cellSize,
        distance = param.contentOf && param.contentOf(cell);

    if (distance >= 0) {
      g.fillStyle = "rgba(128,0,255," + (distance*0.04) + ")";
      g.fillRect(x1, y1, cellSize, cellSize);
      g.fillStyle = 'black';
      g.fillText(distance, (x1+x2)/2, (y1+y2)/2);
    }
    if (!self.northOf(cell)) drawLine(x1, y1, x2, y1);
    if (!self.westOf(cell)) drawLine(x1, y1, x1, y2);
    if (!cell.isLinked(self.eastOf(cell))) drawLine(x2, y1, x2, y2);
    if (!cell.isLinked(self.southOf(cell))) drawLine(x1, y2, x2, y2);
  });
};

module.exports = Grid;
<commit_msg>거리에 따른 alpha값 수정.<commit_after>var Cell = require('./cell'),
    Distance = require('./distance'),
    rand = require('./rand');

function Grid(rows, cols) {
  this.grid = [];
  for (var r = 0; r < rows; r++) {
    this.grid.push([]);
    for (var c = 0; c < cols; c++) {
      this.grid[r].push(new Cell(r, c));
    }
  }
}

Grid.prototype.eachRow = function () {
  var rows = [];
  for (var r = 0, rlen = this.grid.length; r < rlen; r++) {
    rows.push(this.grid[r]);
  }
  return rows;
};

Grid.prototype.eachCell = function () {
  var cells = [];
  for (var r = 0, rlen = this.grid.length; r < rlen; r++) {
    for (var c = 0, clen = this.grid[r].length; c < clen; c++) {
      cells.push(this.grid[r][c]);
    }
  }
  return cells;
};

Grid.prototype.northOf = function (cell) {
  var r = cell.getRow() - 1;
  if (r < 0) {
    return null;
  }
  return this.grid[r][cell.getCol()];
};

Grid.prototype.eastOf = function (cell) {
  var r = cell.getRow(),
      c = cell.getCol() + 1;
  if (c >= this.grid[r].length) {
    return null;
  }
  return this.grid[r][c];
};

Grid.prototype.southOf = function (cell) {
  var r = cell.getRow() + 1;
  if (r >= this.grid.length) {
    return null;
  }
  return this.grid[r][cell.getCol()];
};

Grid.prototype.westOf = function (cell) {
  var c = cell.getCol() - 1;
  if (c < 0) {
    return null;
  }
  return this.grid[cell.getRow()][c];
};

Grid.prototype.neighborsOf = function (cell) {
  var neighbors = [],
      north = this.northOf(cell),
      east = this.eastOf(cell),
      south = this.southOf(cell),
      west = this.westOf(cell);
  if (!!north) neighbors.push(north);
  if (!!east) neighbors.push(east);
  if (!!south) neighbors.push(south);
  if (!!west) neighbors.push(west);
  return neighbors;
};

Grid.prototype.randomCell = function () {
  var r = rand(this.grid.length),
      c = rand(this.grid[0].length);
  return this.grid[r][c];
};

Grid.prototype.distances = function (r, c) {
  var root = this.grid[r||0][c||0],
      distances = new Distance(root),
      frontier = [root];
  while (frontier.length !== 0) {
    var newFrontier = [];
    frontier.forEach(function (cell) {
      cell.links.forEach(function (linked) {
        if (typeof distances.get(linked) === 'number') return;
        distances.set(linked, distances.get(cell)+1);
        newFrontier.push(linked);
      });
    });
    frontier = newFrontier;
  }
  return distances;
};

Grid.prototype.toString = function (contentOf) {
  function body(cell) {
    if (!contentOf) return '   ';
    var content = contentOf(cell);
    if (typeof content !== 'number') return '   ';
    else if (content <  10) return '  '+ content;
    else if (content < 100) return ' ' + content;
    return content;
  }
  var output = '';
  var cols = this.grid[0].length;

  output += '+';
  for (var i = 0; i < cols; i++)
    output += '---+';
  output += '\n';

  for (var r = 0, rlen = this.grid.length; r < rlen; r++) {
    var row = this.grid[r];
    var top = '|', bottom = '+';
    for (var c = 0, clen = row.length; c < clen; c++) {
      var cell = row[c];
      var eastBoundary = cell.isLinked(this.eastOf(cell)) ? ' ' : '|';
      var southBoundary = cell.isLinked(this.southOf(cell)) ? '   ' : '---';
      var corner = '+';
      top += body(cell) + eastBoundary;
      bottom += southBoundary + corner;
    }
    output += top +'\n';
    output += bottom + '\n';
  }
  return output;
};

Grid.prototype.draw = function (param) {
  if (!param.canvasId)
    throw new 'requires canvasId';
  var canvasId = param.canvasId,
      cellSize = param.cellSize || 10;

  var self = this,
      canvas = document.getElementById(canvasId),
      g = canvas.getContext("2d"),
      drawLine = function (x1, y1, x2, y2, color) {
        g.strokeStyle = color || 'black';
        g.beginPath();
        g.moveTo(x1, y1);
        g.lineTo(x2, y2);
        g.lineWidth = 1;
        g.stroke();
      };

  canvas.width = cellSize * this.grid[0].length + 1;
  canvas.height = cellSize * this.grid.length + 1;

  g.translate(0.5, 0.5);
  g.font = '12px "sans serif"';
  g.textAlign = 'center';

  this.eachCell().forEach(function (cell) {
    var x1 = cell.col * cellSize,
        y1 = cell.row * cellSize,
        x2 = (cell.col + 1) * cellSize,
        y2 = (cell.row + 1) * cellSize,
        distance = param.contentOf && param.contentOf(cell);

    if (distance >= 0) {
      g.fillStyle = "rgba(128,0,255," + (distance*0.01) + ")";
      g.fillRect(x1, y1, cellSize, cellSize);
      g.fillStyle = 'black';
      g.fillText(distance, (x1+x2)/2, (y1+y2)/2);
    }
    if (!self.northOf(cell)) drawLine(x1, y1, x2, y1);
    if (!self.westOf(cell)) drawLine(x1, y1, x1, y2);
    if (!cell.isLinked(self.eastOf(cell))) drawLine(x2, y1, x2, y2);
    if (!cell.isLinked(self.southOf(cell))) drawLine(x1, y2, x2, y2);
  });
};

module.exports = Grid;
<|endoftext|>


<commit_before>var backgroundScale = new chroma.scale(["#2d3940", "#fff"]).mode("lab");

document.addEventListener("scroll", function(e) {
  var scroll = window.scrollY;

  /****** STAGE 1 ******
   * HEADER SHRINK AND *
   * DOWN ICON OPACITY *
   *********************/
  var header = document.getElementsByTagName("header")[0];
  var headerTitle = document.getElementsByTagName("h1")[0];
  var downIndicator = document.getElementsByClassName("down-indicator")[0];

  var headerProgress = scroll / (window.innerHeight / 2);

  function setFixedElements(fixed) {
    position = fixed ? "fixed": "absolute";
    header.style.position = position;
    headerTitle.style.position = position;
  }

  function updateHeaderElements(progress) {
    header.style.width = (1 - progress) * 50 + 50 + "vw";
    header.style.height = (1 - progress) * 50 + 50 + "vh";
    downIndicator.style.opacity = 1 - progress;
    document.body.style.backgroundColor = backgroundScale(headerProgress).hex();
  }

  // Starting phase
  if (scroll < 5) {
    setFixedElements(true); // Ensure header elements are fixed
    updateHeaderElements(0);
  // Intermediate phases
  } else if (scroll < window.innerHeight / 2) {
    setFixedElements(true); // Pin header elements
    header.style.top = "50vh";
    headerTitle.style.top = "50vh";
    updateHeaderElements(headerProgress);
  // End phase
  } else {
    setFixedElements(false); // Unpin header elements
    header.style.top = window.innerHeight + "px";
    headerTitle.style.top = window.innerHeight + "px";
    updateHeaderElements(1);
  }
});
<commit_msg>More clean-up<commit_after>var backgroundScale = new chroma.scale(["#2d3940", "#fff"]).mode("lab");

document.addEventListener("scroll", function(e) {
  var scroll = window.scrollY;

  /****** STAGE 1 ******
   * HEADER SHRINK AND *
   * DOWN ICON OPACITY *
   *********************/
  var header = document.getElementsByTagName("header")[0];
  var headerTitle = document.getElementsByTagName("h1")[0];
  var downIndicator = document.getElementsByClassName("down-indicator")[0];

  var headerProgress = scroll / (window.innerHeight / 2);

  function setHeaderElementsPinned(fixed) {
    elements = [header, headerTitle];
    for (var i=0; i<elements.length; i++) {
      elements[i].style.position = fixed ? "fixed" : "absolute";
      elements[i].style.top = fixed ? "50vh" : window.innerHeight + "px";
    }
  }

  function updateHeaderElements(progress) {
    header.style.width = (1 - progress) * 50 + 50 + "vw";
    header.style.height = (1 - progress) * 50 + 50 + "vh";
    downIndicator.style.opacity = 1 - progress;
    document.body.style.backgroundColor = backgroundScale(headerProgress).hex();
  }

  switch(true) {
    case (scroll < 5):
      setHeaderElementsPinned(true);
      updateHeaderElements(0);
      break;

    case (scroll < window.innerHeight / 2):
      setHeaderElementsPinned(true);
      updateHeaderElements(headerProgress);
      break;

    default:
      setHeaderElementsPinned(false);
      updateHeaderElements(1);
  }
});
<|endoftext|>


<commit_before>	var langKey = {
		en: {
			job_title: "Product Developer",
			timeline : "Timeline",
			timeline_sub : "The path to greatness",
			timeline1: "Graduated from Wilfrid Laurier University",
			timeline1_5: "Major in Communications",
			timeline2: "Left for Korea to teach English",
			timeline3: "Came back from Korea",
			timeline3_5: "Completely fed up with teaching.",
			timeline4: "Graduated Web Development Algonquin College ",
			timeline4_5: "Course was too easy, went crazy in the evenings absorbing the net.",
			timeline5: "Front End Developer at ",
			timeline5_5: "Build, learn, repeat. Agility at its finest."	,
			timeline6: "UX Lead Developer at ",
			timeline6_5: "Working with big data and creating cool visualizations! Woah this is cool!",
			timeline7: "Product Developer at ",
			timeline7_5: "Leading teams to bring products to market!",
			timeline8: "Moving back to Korea!",
			timeline8_5: "Looking for remote work.",
			products: "Products",
			products_sub: "List of products I have helped build",
			rebel_content: "With a startup mentality, I guide two teams of 4 in the product development lifecycle. We actively engage our customer during our cycles and implement process to modernise a legacy code base.",
			rebel_role: "Product Developer",
			solink_content: "As UX lead, I designed and lead development on the latest product release. I worked with customers and stakeholders to design a friendly and intuitive experience that works seemlessly on all devices.",
			solink_role: "Lead UX Developer",
			personal: "Personal",
			personal_sub: "List of products I have built in my spare time",
			room_content: "I wanted to build a better way for my landlord and I to communicate. So I built a web app to solve the problem.",
			room_role: "Founder",
			come_content: "A friend of mine and I co-authored an android app that allows friends to communicate real-time events.",
			come_role: "Developer",
			progression: "Developer Progression",
			progression_sub: "How far have I come?",
			prog1: "Simple & Wrong",
			prog2: "Complicated & Wrong",
			prog3: "Complicated & Right",
			prog4: "Simple & Right",
			done: "Done",
			here: "I'm here",
			tags: "Tags",
			tags_sub: "Keywords that feel good.",
			accounts: "Accounts",
			accounts_sub: "A few different ways you can get a hold of me",
			tech: "Tech",
			lifestyle: "Lifestyle",
			travel: "Travel",
			food: "Food",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "Reading, Laughing, Learning, Exercise, Early mornings, Morning Coffee, Wim Hof",
			travel_tags: "Costa Rica, Casco Viejo, Soju, Boracay, Jamaica, AirBnB, Tuk-Tuk, Backpacking ",
			food_tags: "Raw Vegetables, Beer, Korean Food, Cheese & Crackers, Big Macs",
			thanks: "Thanks for taking the time to make it down here"
		},
		kr: {
			job_title: "제품 개발자",
			timeline : "타임 라인",
			timeline_sub : "위대함 에 대한 경로",
			timeline1: "윌 프리드 로리에 대학 졸업",
			timeline1_5: "통신 전공",
			timeline2: "영어를 가르치는 한국 떠났다",
			timeline3: "한국 에서 돌아왔다",
			timeline3_5: "더 이상 가르 칠 싶지 않았다",
			timeline4: "졸업 웹 개발 알곤 퀸 대학",
			timeline4_5: "코스 는 너무 쉬웠다 그물을 흡수 저녁에 미친 갔다.",
			timeline5: "프런트 엔드 개발자 - ",
			timeline5_5: "학습 , 반복 을 구축 할 수 있습니다. 최상의 에서 민첩성 "	,
			timeline6: "UX 리드 개발자 - ",
			timeline6_5: "빅 데이터 로 작업 하고 멋진 시각화를 만들 ! 와우 이 멋지다!",
			timeline7: "제품 개발자 - ",
			timeline7_5: "팀을 선도 하는 것은 시장에 제품을 출시 합니다 !",
			timeline8: "한국으로 다시 이동!",
			timeline8_5: "원격 작업 을 찾고.",
			products: "제품",
			products_sub: "제품 목록 내가 도움이 빌드",
			rebel_content: "시작 의 정신 으로 , 나는 제품 개발 라이프 사이클 에 4 개의 팀을 안내합니다. 우리는 적극적으로 우리의 사이클 동안 우리의 고객 을 참여 하고 기존 코드 기반을 현대화 하는 과정을 구현한다.",
			solink_content: "UX 리드 , 나는 디자인 과 최신 제품 출시 에 리드 개발 . 나는 모든 장치 를 매끄럽게 작동하는 친절하고 직관적 인 경험을 디자인하는 고객 및 이해 관계자들과 일했다.",
			solink_role: "UX 개발자",
			personal: "개인적인",
			personal_sub: "제품 목록 내 여가 시간에 구축 ",
			room_content: "나는 나의 주인 을 위해 더 나은 방법 을 구축 하고 싶어 내가 의사 소통을 할 수 있습니다. 그래서 이 문제를 해결하기 위해 웹 응용 프로그램을 만들었습니다.",
			room_role: "설립자",
			come_content: "내 친구와 나는 친구 가 실시간 이벤트 를 전달 할 수있는 안드로이드 앱을 공동 저술 .",
			come_role: "개발자",
			progression: "Developer Progression",
			progression_sub: "How far have I come?",
			prog1: "Simple & Wrong",
			prog2: "Complicated & Wrong",
			prog3: "Complicated & Right",
			prog4: "Simple & Right",
			done: "Done",
			here: "I'm here",
			tags: "Tags",
			tags_sub: "Keywords that feel good.",
			accounts: "Accounts",
			accounts_sub: "A few different ways you can get a hold of me",
			tech: "Tech",
			lifestyle: "Lifestyle",
			travel: "Travel",
			food: "Food",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "Reading, Laughing, Learning, Exercise, Early mornings, Morning Coffee, Wim Hof",
			travel_tags: "Costa Rica, Casco Viejo, Soju, Boracay, Jamaica, AirBnB, Tuk-Tuk, Backpacking ",
			food_tags: "Raw Vegetables, Beer, Korean Food, Cheese & Crackers, Big Macs",
			thanks: "Thanks for taking the time to make it down here"
		}
	}

	function bindLanguage(lang, elements) {
		for(var i = 0; i < elements.length; i++) {
			var thisItem = $(elements[i])
			var key = thisItem.data("lang-key");

			thisItem.text(langKey[lang][key]);

		}
	}

	var toggles = $("[data-lang-selector]");
	var translations = $("[data-lang-key]");

	bindLanguage("en", translations)

	toggles.on("click", function () {
		var $this = $(this);

		bindLanguage($this.data("lang-selector"), translations);

		$(".selected").removeClass("selected");
		$this.addClass("selected");
	})

<commit_msg>Another run at translations<commit_after>	var langKey = {
		en: {
			job_title: "Product Developer",
			timeline : "Timeline",
			timeline_sub : "The path to greatness",
			timeline1: "Graduated from Wilfrid Laurier University",
			timeline1_5: "Major in Communications",
			timeline2: "Left for Korea to teach English",
			timeline3: "Came back from Korea",
			timeline3_5: "Completely fed up with teaching.",
			timeline4: "Graduated Web Development Algonquin College ",
			timeline4_5: "Course was too easy, went crazy in the evenings absorbing the net.",
			timeline5: "Front End Developer at ",
			timeline5_5: "Build, learn, repeat. Agility at its finest."	,
			timeline6: "UX Lead Developer at ",
			timeline6_5: "Working with big data and creating cool visualizations! Woah this is cool!",
			timeline7: "Product Developer at ",
			timeline7_5: "Leading teams to bring products to market!",
			timeline8: "Moving back to Korea!",
			timeline8_5: "Looking for remote work.",
			products: "Products",
			products_sub: "List of products I have helped build",
			rebel_content: "With a startup mentality, I guide two teams of 4 in the product development lifecycle. We actively engage our customer during our cycles and implement process to modernise a legacy code base.",
			rebel_role: "Product Developer",
			solink_content: "As UX lead, I designed and lead development on the latest product release. I worked with customers and stakeholders to design a friendly and intuitive experience that works seemlessly on all devices.",
			solink_role: "Lead UX Developer",
			personal: "Personal",
			personal_sub: "List of products I have built in my spare time",
			room_content: "I wanted to build a better way for my landlord and I to communicate. So I built a web app to solve the problem.",
			room_role: "Founder",
			come_content: "A friend of mine and I co-authored an android app that allows friends to communicate real-time events.",
			come_role: "Developer",
			progression: "Developer Progression",
			progression_sub: "How far have I come?",
			prog1: "Simple & Wrong",
			prog2: "Complicated & Wrong",
			prog3: "Complicated & Right",
			prog4: "Simple & Right",
			done: "Done",
			here: "I'm here",
			tags: "Tags",
			tags_sub: "Keywords that feel good.",
			accounts: "Accounts",
			accounts_sub: "A few different ways you can get a hold of me",
			tech: "Tech",
			lifestyle: "Lifestyle",
			travel: "Travel",
			food: "Food",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "Reading, Laughing, Learning, Exercise, Early mornings, Morning Coffee, Wim Hof",
			travel_tags: "Costa Rica, Casco Viejo, Soju, Boracay, Jamaica, AirBnB, Tuk-Tuk, Backpacking ",
			food_tags: "Raw Vegetables, Beer, Korean Food, Cheese & Crackers, Big Macs",
			thanks: "Thanks for taking the time to make it down here"
		},
		kr: {
			job_title: "제품 개발자",
			timeline : "타임 라인",
			timeline_sub : "위대함 에 대한 경로",
			timeline1: "윌 프리드 로리에 대학 졸업",
			timeline1_5: "통신 전공",
			timeline2: "영어를 가르치는 한국 떠났다",
			timeline3: "한국 에서 돌아왔다",
			timeline3_5: "더 이상 가르 칠 싶지 않았다",
			timeline4: "졸업 웹 개발 알곤 퀸 대학",
			timeline4_5: "코스 는 너무 쉬웠다 그물을 흡수 저녁에 미친 갔다.",
			timeline5: "프런트 엔드 개발자 - ",
			timeline5_5: "학습 , 반복 을 구축 할 수 있습니다. 최상의 에서 민첩성 "	,
			timeline6: "UX 리드 개발자 - ",
			timeline6_5: "빅 데이터 로 작업 하고 멋진 시각화를 만들 ! 와우 이 멋지다!",
			timeline7: "제품 개발자 - ",
			timeline7_5: "팀을 선도 하는 것은 시장에 제품을 출시 합니다 !",
			timeline8: "한국으로 다시 이동!",
			timeline8_5: "원격 작업 을 찾고.",
			products: "제품",
			products_sub: "제품 목록 내가 도움이 빌드",
			rebel_content: "시작 의 정신 으로 , 나는 제품 개발 라이프 사이클 에 4 개의 팀을 안내합니다. 우리는 적극적으로 우리의 사이클 동안 우리의 고객 을 참여 하고 기존 코드 기반을 현대화 하는 과정을 구현한다.",
			solink_content: "UX 리드 , 나는 디자인 과 최신 제품 출시 에 리드 개발 . 나는 모든 장치 를 매끄럽게 작동하는 친절하고 직관적 인 경험을 디자인하는 고객 및 이해 관계자들과 일했다.",
			solink_role: "UX 개발자",
			personal: "개인적인",
			personal_sub: "제품 목록 내 여가 시간에 구축 ",
			room_content: "나는 나의 주인 을 위해 더 나은 방법 을 구축 하고 싶어 내가 의사 소통을 할 수 있습니다. 그래서 이 문제를 해결하기 위해 웹 응용 프로그램을 만들었습니다.",
			room_role: "설립자",
			come_content: "내 친구와 나는 친구 가 실시간 이벤트 를 전달 할 수있는 안드로이드 앱을 공동 저술 .",
			come_role: "개발자",
			progression: "개발자 진행",
			progression_sub: "나는 얼마나 멀리 왔다 ?",
			prog1: "간단하고 잘못된",
			prog2: "복잡한 및 잘못된",
			prog3: "복잡한 및 수정",
			prog4: "간단하고 및 수정",
			done: "끝난",
			here: "난 여기 있어요",
			tags: "꼬리표",
			tags_sub: "좋은 느낌 키워드",
			accounts: "계정",
			accounts_sub: "몇 가지 방법이 날 의 보류를 얻을 수 있습니다",
			tech: "테크",
			lifestyle: "라이프 스타일",
			travel: "여행",
			food: "식품",
			tech_tags: "Node.js, React, Angular, NoSQL, Deep Learning, AWS, CSS Pre-processing, Task Runners",
			lifestyle_tags: "독서, 웃음, 배우기, 운동, 이른 아침, 모닝 커피, Wim Hof",
			travel_tags: "코스타리카, 카스코 비에 호 , 소주 , 보라카이 , 자메이카 , 에어 비앤비 , 툭 - 툭 , 배낭 여행",
			food_tags: "원시 야채, 맥주, 한국 음식, 치즈 & 크래커, 빅 맥",
			thanks: "Thanks for taking the time to make it down here"
		}
	}

	function bindLanguage(lang, elements) {
		for(var i = 0; i < elements.length; i++) {
			var thisItem = $(elements[i])
			var key = thisItem.data("lang-key");

			thisItem.text(langKey[lang][key]);

		}
	}

	var toggles = $("[data-lang-selector]");
	var translations = $("[data-lang-key]");

	bindLanguage("en", translations)

	toggles.on("click", function () {
		var $this = $(this);

		bindLanguage($this.data("lang-selector"), translations);

		$(".selected").removeClass("selected");
		$this.addClass("selected");
	})

<|endoftext|>


<commit_before>var Lang = {
    supportedLang: [
        {
            key: 'ja-JP',
            text: '日本語'
        },
        {
            key: 'zh-TW',
            text: '正體中文'
        },
        {
            key: 'en-US',
            text: 'English'
        },
        {
            key: 'zh-CN',
            text: '简体中文'
        }],
    get: function () {
        var lang = localStorage["lang"] || navigator.language || navigator.browserLanguage;
        if (_.any(this.supportedLang, function (o) { return o.key == lang }) == false) {
            lang = 'ja-JP';
        }
        localStorage["lang"] = lang;
        $('#currentLang').text(_.find(this.supportedLang, function (o) {
            return o.key == lang;
        }).text);
        return lang;
    },
    set: function (lang) {
        localStorage["lang"] = lang;
    },
};
//navbar
Lang["list"] = { "ja-JP": "図鑑", "zh-TW": "圖鑑", "en-US": "Encyclopedia", "zh-CN": "图鉴" };
Lang["search"] = { "ja-JP": "検索", "zh-TW": "搜索", "en-US": "Search", "zh-CN": "搜索" };
Lang["category"] = { "ja-JP": "", "zh-TW": "分類", "en-US": "Category", "zh-CN": "分类" };
Lang["about"] = { "ja-JP": "", "zh-TW": "", "en-US": "About", "zh-CN": "关于" };
Lang["ui"] = { "ja-JP": "", "zh-TW": "", "en-US": "UI", "zh-CN": "界面语言" };
Lang["data"] = { "ja-JP": "", "zh-TW": "", "en-US": "Data", "zh-CN": "数据语言" };
//unit detail
Lang["life"] = { "ja-JP": "HP", "zh-TW": "HP", "en-US": "HP", "zh-CN": "HP" };
Lang["attack"] = { "ja-JP": "攻撃力", "zh-TW": "攻擊力", "en-US": "ATK", "zh-CN": "攻击力" };
Lang["heal"] = { "ja-JP": "回復", "zh-TW": "回復力", "en-US": "REC", "zh-CN": "回复" };
Lang["pt"] = { "ja-JP": "進化pt", "zh-TW": "進化點數", "en-US": "EV Pts", "zh-CN": "进化pt" };
Lang["exp"] = { "ja-JP": "経験値", "zh-TW": "經驗值", "en-US": "EXP", "zh-CN": "经验值" };
Lang["evolve"] = { "ja-JP": "進化", "zh-TW": "進化", "en-US": "Evolve", "zh-CN": "进化" };
Lang["evolvept"] = { "ja-JP": "必要進化pt", "zh-TW": "必須進化點數", "en-US": "Evolve", "zh-CN": "进化所需pt" };
Lang["awakening"] = { "ja-JP": "覚醒pt", "zh-TW": "覺醒點數", "en-US": "Awakening", "zh-CN": "觉醒pt" };
Lang["skill"] = { "ja-JP": "スキル", "zh-TW": "技能", "en-US": "Skill", "zh-CN": "技能" };
Lang["party"] = { "ja-JP": "パーティスキル", "zh-TW": "隊伍技能", "en-US": "Party Skill", "zh-CN": "被动技能" };
Lang["active"] = { "ja-JP": "アクティブスキル", "zh-TW": "主動技能", "en-US": "Active Skill", "zh-CN": "主动技能" };
Lang["panel"] = { "ja-JP": "パネルスキル", "zh-TW": "方塊技能", "en-US": "Panel Skill", "zh-CN": "光板技能" };
Lang["limit"] = { "ja-JP": "リミットスキル", "zh-TW": "極限技能", "en-US": "Limit Skill", "zh-CN": "Limit技能" };
Lang["soul"] = { "ja-JP": "消費ソウル", "zh-TW": "消耗魂", "en-US": "Souls", "zh-CN": "消耗魂" };
Lang["story"] = { "ja-JP": "ストーリー", "zh-TW": "故事", "en-US": "Story", "zh-CN": "故事" };
Lang["cutin"] = { "ja-JP": "カットイン", "zh-TW": "切入", "en-US": "Special Moves", "zh-CN": "Cutin" };
Lang["accessory"] = { "ja-JP": "アクセサリー", "zh-TW": "飾品", "en-US": "Accessory", "zh-CN": "饰品" };
//search
Lang["clear"] = { "ja-JP": "", "zh-TW": "", "en-US": "Clear", "zh-CN": "" };
Lang["searchfor"] = { "ja-JP": "", "zh-TW": "", "en-US": "Search for...(Currently only support Japanese)", "zh-CN": "" };
Lang["general"] = { "ja-JP": "", "zh-TW": "", "en-US": "General", "zh-CN": "" };
Lang["name"] = { "ja-JP": "", "zh-TW": "", "en-US": "Name", "zh-CN": "" };
Lang["showonly100"] = { "ja-JP": "", "zh-TW": "", "en-US": "Show only first 100 results.", "zh-CN": "" };
Lang["rarity"] = { "ja-JP": "", "zh-TW": "", "en-US": "Rarity", "zh-CN": "" };
Lang["class"] = { "ja-JP": "", "zh-TW": "", "en-US": "Class", "zh-CN": "" };
Lang["attribute"] = { "ja-JP": "", "zh-TW": "", "en-US": "Attribute", "zh-CN": "" };
Lang["subattribute"] = { "ja-JP": "", "zh-TW": "", "en-US": "SubAttribute", "zh-CN": "" };
Lang["all"] = { "ja-JP": "", "zh-TW": "", "en-US": "All", "zh-CN": "全部" };<commit_msg>update translation<commit_after>var Lang = {
    supportedLang: [
        {
            key: 'ja-JP',
            text: '日本語'
        },
        {
            key: 'zh-TW',
            text: '正體中文'
        },
        {
            key: 'en-US',
            text: 'English'
        },
        {
            key: 'zh-CN',
            text: '简体中文'
        }],
    get: function () {
        var lang = localStorage["lang"] || navigator.language || navigator.browserLanguage;
        if (_.any(this.supportedLang, function (o) { return o.key == lang }) == false) {
            lang = 'ja-JP';
        }
        localStorage["lang"] = lang;
        $('#currentLang').text(_.find(this.supportedLang, function (o) {
            return o.key == lang;
        }).text);
        return lang;
    },
    set: function (lang) {
        localStorage["lang"] = lang;
    },
};
//navbar
Lang["list"] = { "ja-JP": "図鑑", "zh-TW": "圖鑑", "en-US": "Encyclopedia", "zh-CN": "图鉴" };
Lang["search"] = { "ja-JP": "検索", "zh-TW": "搜索", "en-US": "Search", "zh-CN": "搜索" };
Lang["category"] = { "ja-JP": "", "zh-TW": "分類", "en-US": "Category", "zh-CN": "分类" };
Lang["about"] = { "ja-JP": "", "zh-TW": "關於", "en-US": "About", "zh-CN": "关于" };
Lang["ui"] = { "ja-JP": "", "zh-TW": "界面語言", "en-US": "UI", "zh-CN": "界面语言" };
Lang["data"] = { "ja-JP": "", "zh-TW": "資料語言", "en-US": "Data", "zh-CN": "数据语言" };
//unit detail
Lang["life"] = { "ja-JP": "HP", "zh-TW": "HP", "en-US": "HP", "zh-CN": "HP" };
Lang["attack"] = { "ja-JP": "攻撃力", "zh-TW": "攻擊力", "en-US": "ATK", "zh-CN": "攻击力" };
Lang["heal"] = { "ja-JP": "回復", "zh-TW": "回復力", "en-US": "REC", "zh-CN": "回复" };
Lang["pt"] = { "ja-JP": "進化pt", "zh-TW": "進化點數", "en-US": "EV Pts", "zh-CN": "进化pt" };
Lang["exp"] = { "ja-JP": "経験値", "zh-TW": "經驗值", "en-US": "EXP", "zh-CN": "经验值" };
Lang["evolve"] = { "ja-JP": "進化", "zh-TW": "進化", "en-US": "Evolve", "zh-CN": "进化" };
Lang["evolvept"] = { "ja-JP": "必要進化pt", "zh-TW": "必須進化點數", "en-US": "Evolve", "zh-CN": "进化所需pt" };
Lang["awakening"] = { "ja-JP": "覚醒pt", "zh-TW": "覺醒點數", "en-US": "Awakening", "zh-CN": "觉醒pt" };
Lang["skill"] = { "ja-JP": "スキル", "zh-TW": "技能", "en-US": "Skill", "zh-CN": "技能" };
Lang["party"] = { "ja-JP": "パーティスキル", "zh-TW": "隊伍技能", "en-US": "Party Skill", "zh-CN": "被动技能" };
Lang["active"] = { "ja-JP": "アクティブスキル", "zh-TW": "主動技能", "en-US": "Active Skill", "zh-CN": "主动技能" };
Lang["panel"] = { "ja-JP": "パネルスキル", "zh-TW": "方塊技能", "en-US": "Panel Skill", "zh-CN": "光板技能" };
Lang["limit"] = { "ja-JP": "リミットスキル", "zh-TW": "極限技能", "en-US": "Limit Skill", "zh-CN": "Limit技能" };
Lang["soul"] = { "ja-JP": "消費ソウル", "zh-TW": "消耗魂", "en-US": "Souls", "zh-CN": "消耗魂" };
Lang["story"] = { "ja-JP": "ストーリー", "zh-TW": "故事", "en-US": "Story", "zh-CN": "故事" };
Lang["cutin"] = { "ja-JP": "カットイン台詞", "zh-TW": "切入台詞", "en-US": "Special Move Lines", "zh-CN": "特写台词" };
Lang["accessory"] = { "ja-JP": "アクセサリー", "zh-TW": "飾品", "en-US": "Accessory", "zh-CN": "饰品" };
//search<|endoftext|>


<commit_before>/**
 * various keyword lists used in the ORS application
 */

list = {
	languages: ['de','en','es','fr','it','nl', 'hu','ru' ,'cz','pl','ua','cn_simple','cn'],

	routingLanguages : ['en', 'de', 'pl', 'bg', 'cz', 'nl', 'hr', 'hu', 'nl_BE', 'es', 'eo', 'fi', 'fr', 'it', 'pt_BR', 'ro', 'ru', 'se', 'dk', 'tr', 'ca', 'ja', 'no', 'vi', 'nb', 'de-rheinl', 'de-opplat', 'de-berlin', 'de-swabia', 'de-ruhrpo', 'de-at-ooe', 'de-bay'],

	distanceUnits: ['m', 'km', 'yd', 'mi'],
	distanceUnitsPreferences : ['m', 'yd'],
	//as visible in the user preferences popup
	distanceUnitsInPopup: ['m / km', 'yd / mi'],

	version : ['standardVersion', 'extendedVersion'],

	poiCategories: ['amenity', 'public_tran', 'shop', 'tourism', 'leisure', 'sport'],

	poiTypes: new Hash({
		'amenity': ['atm', 'bank', 'bureau_de_change', 'biergarten', 'bus_station', 'cafe', 'cinema', 'college', 'courthouse',
			'fast_food', 'fuel', 'hospital', 'library', 'nightclub', 'parking', 'pharmacy', 'place_of_worship', 'police',
			'post_box', 'post_office', 'pub', 'public_building', 'restaurant', 'school', 'taxi', 'telephone', 'theatre',
			'toilets', 'townhall', 'university'],
		'public_tran': ['bus_stop', 'bus_station', 'railway_station', 'tram_stop', 'subway_entrance', 'parking'],
		'shop': ['supermarket', 'convenience', 'bakery', 'butcher', 'kiosk'],
		'tourism': ['information','hotel', 'motel', 'guest_house', 'hostel', 'camp_site', 'caravan_site', 'chalet', 'viewpoint'],
		'leisure': ['sports_centre', 'golf_course', 'stadium', 'track', 'pitch', 'water_park', 'marina', 'slipway', 'fishing', 'nature_reserve',
			'park', 'playground', 'garden', 'ice_rink', 'miniature_golf'],
		'sport': ['9pin', '10pin', 'archery', 'athletics', 'australian_football', 'baseball', 'basketball', 'beachvolleyball', 'boules', 'bowls',
			'canoe', 'chess', 'climbing','cricket', 'cricket_nets', 'croquet', 'cycling', 'diving', 'dog_racing', 'equestrian', 'football', 'golf', 'gymnastics',
			'hockey', 'horse_racing', 'korfball', 'motor', 'orienteering', 'paddle_tennis', 'squash', 'paragliding', 'pelota', 'racquet', 'rowing', 'rugby',
			'shooting', 'skating', 'skateboard', 'skiing', 'soccer', 'swimming', 'table_tennis', 'team_handball', 'tennis', 'volleyball']
	}),

	//please make sure that each category contains at least one element. all names in the hash have to be unique.
	routePreferences: new Hash({
		'car': ['Fastest', 'Shortest'],
		'bicycle': ['Bicycle', 'BicycleSafety', 'BicycleRoute', 'BicycleMTB', 'BicycleRacer'],
		'pedestrian': ['Pedestrian'],
		'truck': [['HeavyTruck'],['goods', 'hgv', 'bus', 'agricultural', 'forestry']],
		'wheelchair': ['Wheelchair']
	}),

	routeAvoidables : ['Highway', 'Tollway', 'Unpavedroads', 'Ferry'],

	truckParams : ['value_length_slide', 'value_height_slide', 'value_weigth_slide',, 'value_width_slide'],

	routePreferencesImages: new Hash({
		'car': ['img/picto-car.png', 'img/picto-car-high.png'],
		'bicycle': ['img/picto-bike.png', 'img/picto-bike-high.png'],
		'pedestrian' : ['img/picto-dude.png', 'img/picto-dude-high.png'],
		'truck' : ['img/picto-truck.png', 'img/picto-truck-high.png'],
		'wheelchair' : ['img/picto-wheelchair.png', 'img/picto-wheelchair-high.png']
	}),

	//please make sure that each category contains at least one element. all names in the hash have to be unique.
	wheelchairParameters: new Hash({

		'Surface': ['concrete', 'cobblestone:flattened', 'cobblestone', 'compacted', 'any'],
		'Smoothness': ['excellent', 'good', 'intermediate', 'bad', 'any'],
		'Tracktype': ['grade1', 'grade2', 'grade3', 'grade4', 'any'],
		'Incline': ['3', '6', '10', '15', '31'],
		'SlopedCurb': ['0.03', '0.06', '0.1', '0.31']
	}),
};<commit_msg>chinese routing instrcutions<commit_after>/**
 * various keyword lists used in the ORS application
 */

list = {
	languages: ['de','en','es','fr','it','nl', 'hu','ru' ,'cz','pl','ua','cn_simple','cn'],

	routingLanguages : ['en', 'de', 'pl', 'bg', 'cn','cn_simple','cz', 'nl', 'hr', 'hu', 'nl_BE', 'es', 'eo', 'fi', 'fr', 'it', 'pt_BR', 'ro', 'ru', 'se', 'dk', 'tr', 'ca', 'ja', 'no', 'vi', 'nb', 'de-rheinl', 'de-opplat', 'de-berlin', 'de-swabia', 'de-ruhrpo', 'de-at-ooe', 'de-bay'],

	distanceUnits: ['m', 'km', 'yd', 'mi'],
	distanceUnitsPreferences : ['m', 'yd'],
	//as visible in the user preferences popup
	distanceUnitsInPopup: ['m / km', 'yd / mi'],

	version : ['standardVersion', 'extendedVersion'],

	poiCategories: ['amenity', 'public_tran', 'shop', 'tourism', 'leisure', 'sport'],

	poiTypes: new Hash({
		'amenity': ['atm', 'bank', 'bureau_de_change', 'biergarten', 'bus_station', 'cafe', 'cinema', 'college', 'courthouse',
			'fast_food', 'fuel', 'hospital', 'library', 'nightclub', 'parking', 'pharmacy', 'place_of_worship', 'police',
			'post_box', 'post_office', 'pub', 'public_building', 'restaurant', 'school', 'taxi', 'telephone', 'theatre',
			'toilets', 'townhall', 'university'],
		'public_tran': ['bus_stop', 'bus_station', 'railway_station', 'tram_stop', 'subway_entrance', 'parking'],
		'shop': ['supermarket', 'convenience', 'bakery', 'butcher', 'kiosk'],
		'tourism': ['information','hotel', 'motel', 'guest_house', 'hostel', 'camp_site', 'caravan_site', 'chalet', 'viewpoint'],
		'leisure': ['sports_centre', 'golf_course', 'stadium', 'track', 'pitch', 'water_park', 'marina', 'slipway', 'fishing', 'nature_reserve',
			'park', 'playground', 'garden', 'ice_rink', 'miniature_golf'],
		'sport': ['9pin', '10pin', 'archery', 'athletics', 'australian_football', 'baseball', 'basketball', 'beachvolleyball', 'boules', 'bowls',
			'canoe', 'chess', 'climbing','cricket', 'cricket_nets', 'croquet', 'cycling', 'diving', 'dog_racing', 'equestrian', 'football', 'golf', 'gymnastics',
			'hockey', 'horse_racing', 'korfball', 'motor', 'orienteering', 'paddle_tennis', 'squash', 'paragliding', 'pelota', 'racquet', 'rowing', 'rugby',
			'shooting', 'skating', 'skateboard', 'skiing', 'soccer', 'swimming', 'table_tennis', 'team_handball', 'tennis', 'volleyball']
	}),

	//please make sure that each category contains at least one element. all names in the hash have to be unique.
	routePreferences: new Hash({
		'car': ['Fastest', 'Shortest'],
		'bicycle': ['Bicycle', 'BicycleSafety', 'BicycleRoute', 'BicycleMTB', 'BicycleRacer'],
		'pedestrian': ['Pedestrian'],
		'truck': [['HeavyTruck'],['goods', 'hgv', 'bus', 'agricultural', 'forestry']],
		'wheelchair': ['Wheelchair']
	}),

	routeAvoidables : ['Highway', 'Tollway', 'Unpavedroads', 'Ferry'],

	truckParams : ['value_length_slide', 'value_height_slide', 'value_weigth_slide',, 'value_width_slide'],

	routePreferencesImages: new Hash({
		'car': ['img/picto-car.png', 'img/picto-car-high.png'],
		'bicycle': ['img/picto-bike.png', 'img/picto-bike-high.png'],
		'pedestrian' : ['img/picto-dude.png', 'img/picto-dude-high.png'],
		'truck' : ['img/picto-truck.png', 'img/picto-truck-high.png'],
		'wheelchair' : ['img/picto-wheelchair.png', 'img/picto-wheelchair-high.png']
	}),

	//please make sure that each category contains at least one element. all names in the hash have to be unique.
	wheelchairParameters: new Hash({

		'Surface': ['concrete', 'cobblestone:flattened', 'cobblestone', 'compacted', 'any'],
		'Smoothness': ['excellent', 'good', 'intermediate', 'bad', 'any'],
		'Tracktype': ['grade1', 'grade2', 'grade3', 'grade4', 'any'],
		'Incline': ['3', '6', '10', '15', '31'],
		'SlopedCurb': ['0.03', '0.06', '0.1', '0.31']
	}),
};<|endoftext|>


<commit_before>var notifier = require('node-notifier');
var argv = require('yargs').argv;

module.exports = (function () {
    var projectName = "novicell-gulp";

    var projectPath = "./";
    var bowerPath = projectPath + "vendor/bower"; // remember to edit .bowerrc aswell (for CLI)
    var distPath = projectPath + "dist";
    var typescriptPath = projectPath + "scripts/typescript";
    var cleanPaths = [distPath];
    var preprocessor = "less"; //choose between "less" or "scss"
    var enableTypescript = true; // Set to false to disable

    return {
        // ------------- Bundles -------------
        bundles: [
            {
                name: "vendor",
                ignorePlugins: ["jscs", "jshint", "watch"], // add "minify", to ignore minifaction on a bundle
                scripts: [
                    bowerPath + "/svg4everybody/dist/svg4everybody.js",
                    bowerPath + "/jquery/dist/jquery.js"
                ]
            },
            {
                // For styling Umbraco Grid editors in backoffice
                name: "backofficemaster",
                scripts: [
                    projectPath + "scripts/backofficemaster.js"
                ],
                styles: ["./" + preprocessor + "/backofficemaster." + preprocessor],
            },
            {
                name: "master",
                ignorePlugins: ["jscs"],
                scripts: [
                    projectPath + "scripts/components/novicell.js",
                    projectPath + "scripts/components/novicell.debounce.js",
                    projectPath + "scripts/components/novicell.visible.js",
                    projectPath + "scripts/components/novicell.lazyloadResponsive.js",
                    projectPath + "scripts/components/novicell.embed.js",
                    // projectPath + "scripts/components/novicell.overlay.js",
                    projectPath + "scripts/components/novicell.cookieinfo.js",
                    projectPath + "scripts/components/novicell.map.js",
                    projectPath + "scripts/master.js"
                ],
                styles: [projectPath + preprocessor + "/master." + preprocessor],
                images: [projectPath + "images/**/*.{jpg,png,svg,gif}"],
                icons: [projectPath + "icons/**/*.svg"]
            }
        ],

        // ------------- Styles -------------
        stylesDist: distPath + "/css",
        stylesVendorPrefixes: [
            "last 2 version",
            "safari 5",
            "ie 9",
            "opera 12.1",
            "ios 8",
            "android 4"
        ],

        // ------------- Scripts -------------
        scriptsDist: distPath + "/scripts",

        // ------------- Icons ---------------
        iconsDist: distPath,
        spriteConfig: {
            shape : {
                // Set maximum dimensions
                dimension       : {
                    maxWidth    : 32,
                    maxHeight   : 32
                }
            },
            mode : {
                view : {
                    bust : false,
                    render : {
                        less : true
                    },
                    dest : 'icons',
                    sprite : 'icons-css.svg'
                },
                symbol : {
                    dest : 'icons',
                    sprite : 'icons.svg'
                }
            }
        },

        // ------------- Fonts -------------
        fontsDist: distPath + "/fonts",

        // ------------- Images -------------
        imagesDist: distPath + "/images",
        imagesOptimizationLevel: 5,
        imagesProgressive: true,
        imagesInterlaced: true,

        // ------------- Livereload ---------
        livereloadPort: 35729,
        livereloadPaths: [
            "./dist/scripts/*.js",
            "./dist/css/*.css",
            "./Views/**/*.cshtml"
        ],

        // ------------- Watch -------------
        watchImages: [ projectPath + "images/**/*", projectPath + '!images/icons/*' ],
        watchIcons: [ projectPath + "images/icons/*" ],
        watchFonts: [ projectPath + "fonts/*" ],
        watchScripts: [
            projectPath + "scripts/**/*.js",
            projectPath + "vendor/**/*.js"
        ],
        watchStyles: [
            projectPath + preprocessor + "/**/*." + preprocessor,
            projectPath + "vendor/**/*.{less, scss}"
        ],

        // ------------- Copy on build --------
        buildCopy: [{
            from: projectPath + "fonts/**/*",
            to: distPath  + "/fonts"
        }],

        // ------------- Tasks -------------
        loadTasks: [
            "bower", "typescript", "styles",
            "scripts", "images", "icons",
            "copy", "watch", "build",
        ],
        buildTasks: [
            "styles", "typescript", "scripts",
            "images", "icons", "copy",
        ],

        // ------------- Return Paths -------------
        projectPath: projectPath,
        bowerPath: bowerPath,
        cleanPaths: cleanPaths,
        typescriptPath: typescriptPath,
        enableTypescript: enableTypescript,
        preprocessor: preprocessor,

        // ---------- Errorhandler ------
        errorHandler: function(taskName)
        {
            return function (e) {
                notifier.notify({
                    "title": taskName,
                    "message": "An error occured in the " + e.plugin + " plugin."
                });
                console.log(e.message);
                this.emit("end");
            };
        }
    }
})();
<commit_msg>Update config.js<commit_after>var notifier = require('node-notifier');
var argv = require('yargs').argv;

module.exports = (function () {
    var projectName = "novicell-gulp";

    var projectPath = "./";
    var bowerPath = projectPath + "vendor/bower"; // remember to edit .bowerrc aswell (for CLI)
    var distPath = projectPath + "dist";
    var typescriptPath = projectPath + "scripts/typescript";
    var cleanPaths = [distPath];
    var preprocessor = "less"; //choose between "less" or "scss"
    var enableTypescript = false; // Set to false to disable

    return {
        // ------------- Bundles -------------
        bundles: [
            {
                name: "vendor",
                ignorePlugins: ["jscs", "jshint", "watch"], // add "minify", to ignore minifaction on a bundle
                scripts: [
                    bowerPath + "/svg4everybody/dist/svg4everybody.js",
                    bowerPath + "/jquery/dist/jquery.js"
                ]
            },
            {
                // For styling Umbraco Grid editors in backoffice
                name: "backofficemaster",
                scripts: [
                    projectPath + "scripts/backofficemaster.js"
                ],
                styles: ["./" + preprocessor + "/backofficemaster." + preprocessor],
            },
            {
                name: "master",
                ignorePlugins: ["jscs"],
                scripts: [
                    projectPath + "scripts/components/novicell.js",
                    projectPath + "scripts/components/novicell.debounce.js",
                    projectPath + "scripts/components/novicell.visible.js",
                    projectPath + "scripts/components/novicell.lazyloadResponsive.js",
                    projectPath + "scripts/components/novicell.embed.js",
                    // projectPath + "scripts/components/novicell.overlay.js",
                    projectPath + "scripts/components/novicell.cookieinfo.js",
                    projectPath + "scripts/components/novicell.map.js",
                    projectPath + "scripts/master.js"
                ],
                styles: [projectPath + preprocessor + "/master." + preprocessor],
                images: [projectPath + "images/**/*.{jpg,png,svg,gif}"],
                icons: [projectPath + "icons/**/*.svg"]
            }
        ],

        // ------------- Styles -------------
        stylesDist: distPath + "/css",
        stylesVendorPrefixes: [
            "last 2 version",
            "safari 5",
            "ie 9",
            "opera 12.1",
            "ios 8",
            "android 4"
        ],

        // ------------- Scripts -------------
        scriptsDist: distPath + "/scripts",

        // ------------- Icons ---------------
        iconsDist: distPath,
        spriteConfig: {
            shape : {
                // Set maximum dimensions
                dimension       : {
                    maxWidth    : 32,
                    maxHeight   : 32
                }
            },
            mode : {
                view : {
                    bust : false,
                    render : {
                        less : true
                    },
                    dest : 'icons',
                    sprite : 'icons-css.svg'
                },
                symbol : {
                    dest : 'icons',
                    sprite : 'icons.svg'
                }
            }
        },

        // ------------- Fonts -------------
        fontsDist: distPath + "/fonts",

        // ------------- Images -------------
        imagesDist: distPath + "/images",
        imagesOptimizationLevel: 5,
        imagesProgressive: true,
        imagesInterlaced: true,

        // ------------- Livereload ---------
        livereloadPort: 35729,
        livereloadPaths: [
            "./dist/scripts/*.js",
            "./dist/css/*.css",
            "./Views/**/*.cshtml"
        ],

        // ------------- Watch -------------
        watchImages: [ projectPath + "images/**/*", projectPath + '!images/icons/*' ],
        watchIcons: [ projectPath + "images/icons/*" ],
        watchFonts: [ projectPath + "fonts/*" ],
        watchScripts: [
            projectPath + "scripts/**/*.js",
            projectPath + "vendor/**/*.js"
        ],
        watchStyles: [
            projectPath + preprocessor + "/**/*." + preprocessor,
            projectPath + "vendor/**/*.{less, scss}"
        ],

        // ------------- Copy on build --------
        buildCopy: [{
            from: projectPath + "fonts/**/*",
            to: distPath  + "/fonts"
        }],

        // ------------- Tasks -------------
        loadTasks: [
            "bower", "typescript", "styles",
            "scripts", "images", "icons",
            "copy", "watch", "build",
        ],
        buildTasks: [
            "styles", "typescript", "scripts",
            "images", "icons", "copy",
        ],

        // ------------- Return Paths -------------
        projectPath: projectPath,
        bowerPath: bowerPath,
        cleanPaths: cleanPaths,
        typescriptPath: typescriptPath,
        enableTypescript: enableTypescript,
        preprocessor: preprocessor,

        // ---------- Errorhandler ------
        errorHandler: function(taskName)
        {
            return function (e) {
                notifier.notify({
                    "title": taskName,
                    "message": "An error occured in the " + e.plugin + " plugin."
                });
                console.log(e.message);
                this.emit("end");
            };
        }
    }
})();
<|endoftext|>