<commit_before>var drawModule = (function () {

  var bodySnake = function(x, y) {
        ctx.fillStyle = 'green';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.strokeStyle = 'darkgreen';
        ctx.strokeRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
  }

  var pizza = function(x, y) {
        ctx.fillStyle = 'red';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.fillStyle = 'red';
        ctx.fillRect(x*snakeSize+1, y*snakeSize+1, snakeSize-2, snakeSize-2);
  }

  var scoreText = function() {
    var score_text = "Score: " + score;
    ctx.fillStyle = 'blue';
    ctx.fillText(score_text, 145, h-5);
  }

  var drawSnake = function() {
      var length = 4;
      snake = [];
      for (var i = length-1; i>=0; i--) {
          snake.push({x:i, y:0});
      }
  }

  var paint = function(){
      ctx.fillStyle = 'lightgrey';
      ctx.fillRect(0, 0, w, h);
      ctx.strokeStyle = 'black';
      ctx.strokeRect(0, 0, w, h);

      btn.setAttribute('disabled', true);

      var snakeX = snake[0].x;
      var snakeY = snake[0].y;

      if (direction == 'right') {
        snakeX++; }
      else if (direction == 'left') {
        snakeX--; }
      else if (direction == 'up') {
        snakeY--;
      } else if(direction == 'down') {
        snakeY++; }

      if (snakeX == -1 || snakeX == w/snakeSize || snakeY == -1 || snakeY == h/snakeSize || checkCollision(snakeX, snakeY, snake)) {
          //restart game
          btn.removeAttribute('disabled', true);
          score = 0;
          ctx.clearRect(0,0,w,h);
          gameloop = clearInterval(gameloop);
          return;
        }

        if(snakeX == food.x && snakeY == food.y) {
          var tail = {x: snakeX, y: snakeY}; //Create a new head instead of moving the tail
          score ++;

          createFood(); //Create new food
        } else {
          var tail = snake.pop(); //pops out the last cell
          tail.x = snakeX;
          tail.y = snakeY;
        }
        //The snake can now eat the food.
        snake.unshift(tail); //puts back the tail as the first cell

        for(var i = 0; i < snake.length; i++) {
          bodySnake(snake[i].x, snake[i].y);
        }

        pizza(food.x, food.y);
        scoreText();
  }

  var createFood = function() {
      food = {
        x: Math.floor((Math.random() * 30) + 1),
        y: Math.floor((Math.random() * 30) + 1)
      }

      for (var i=0; i>snake.length; i++) {
        var snakeX = snake[i].x;
        var snakeY = snake[i].y;

        if (food.x===snakeX && food.y === snakeY || food.y === snakeY && food.x===snakeX) {
          food.x = Math.floor((Math.random() * 30) + 1);
          food.y = Math.floor((Math.random() * 30) + 1);
        }
      }
  }

  var checkCollision = function(x, y, array) {
      for(var i = 0; i < array.length; i++) {
        if(array[i].x === x && array[i].y === y)
        return true;
      }
      return false;
  }

  var init = function(){
      direction = 'down';
      drawSnake();
      createFood();
      gameloop = setInterval(paint, 80);
  }

    return {
      init : init
    };

}());
<commit_msg>Update draw.js<commit_after>var drawModule = (function () {

  var bodySnake = function(x, y) {
        ctx.fillStyle = 'green';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.strokeStyle = 'darkgreen';
        ctx.strokeRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
  }

  var pizza = function(x, y) {
        ctx.fillStyle = 'red';
        ctx.fillRect(x*snakeSize, y*snakeSize, snakeSize, snakeSize);
        ctx.fillStyle = 'darkred';
        ctx.fillRect(x*snakeSize+1, y*snakeSize+1, snakeSize-2, snakeSize-2);
  }

  var scoreText = function() {
    var score_text = "Score: " + score;
    ctx.fillStyle = 'blue';
    ctx.fillText(score_text, 145, h-5);
  }

  var drawSnake = function() {
      var length = 4;
      snake = [];
      for (var i = length-1; i>=0; i--) {
          snake.push({x:i, y:0});
      }
  }

  var paint = function(){
      ctx.fillStyle = 'black';
      ctx.fillRect(0, 0, w, h);
      ctx.strokeStyle = 'black';
      ctx.strokeRect(0, 0, w, h);

      btn.setAttribute('disabled', true);

      var snakeX = snake[0].x;
      var snakeY = snake[0].y;

      if (direction == 'right') {
        snakeX++; }
      else if (direction == 'left') {
        snakeX--; }
      else if (direction == 'up') {
        snakeY--;
      } else if(direction == 'down') {
        snakeY++; }

      if (snakeX == -1 || snakeX == w/snakeSize || snakeY == -1 || snakeY == h/snakeSize || checkCollision(snakeX, snakeY, snake)) {
          //restart game
          btn.removeAttribute('disabled', true);
          score = 0;
          ctx.clearRect(0,0,w,h);
          gameloop = clearInterval(gameloop);
          return;
        }

        if(snakeX == food.x && snakeY == food.y) {
          var tail = {x: snakeX, y: snakeY}; //Create a new head instead of moving the tail
          score ++;

          createFood(); //Create new food
        } else {
          var tail = snake.pop(); //pops out the last cell
          tail.x = snakeX;
          tail.y = snakeY;
        }
        //The snake can now eat the food.
        snake.unshift(tail); //puts back the tail as the first cell

        for(var i = 0; i < snake.length; i++) {
          bodySnake(snake[i].x, snake[i].y);
        }

        pizza(food.x, food.y);
        scoreText();
  }

  var createFood = function() {
      food = {
        x: Math.floor((Math.random() * 30) + 1),
        y: Math.floor((Math.random() * 30) + 1)
      }

      for (var i=0; i>snake.length; i++) {
        var snakeX = snake[i].x;
        var snakeY = snake[i].y;

        if (food.x===snakeX && food.y === snakeY || food.y === snakeY && food.x===snakeX) {
          food.x = Math.floor((Math.random() * 30) + 1);
          food.y = Math.floor((Math.random() * 30) + 1);
        }
      }
  }

  var checkCollision = function(x, y, array) {
      for(var i = 0; i < array.length; i++) {
        if(array[i].x === x && array[i].y === y)
        return true;
      }
      return false;
  }

  var init = function(){
      direction = 'down';
      drawSnake();
      createFood();
      gameloop = setInterval(paint, 80);
  }

    return {
      init : init
    };

}());
<|endoftext|>


<commit_before>$(document).ready(function () {

    drawGrid(0, 0);

    addKeysClickBehavior();

    $(window).resize(function () {
        drawGrid(0, 0);
    });

});

function addCellClickBehavior() {
    $("#grid td.cell").unbind("click");
    $("#grid td.cell").each(function () {
        $(this).click(function () {
            flagCell($(this));
        });
    });
}

function deleteSelectedCell() {
    if (selectedCell) {
        selectedCell.html("");
        selectedCell.removeClass("filled-cell rooted-cell divided-cell");
        flagCell(getPreviousFilledCell());
    }
}

function returnSelectedCell() {
    if (selectedCell.nextAll("td.cell:eq(" + (columnsNumber - 1) + ")")) {
        for (let j = CELL_SIDE; j <= $('#grid').width(); j += CELL_SIDE) {
            $('#grid').append("	");
            rowsNumber++;
        }
        addCellClickBehavior(); // flag current cell selected
        flagCell(selectedCell.nextAll("td.cell:eq(" + (columnsNumber - 1) + ")"));
    }

}

function addSpaceCell() {
    if (selectedCell.next("td.cell")) {
        flagCell(selectedCell.next("td.cell"));
    }
}

function copyKeyToSelectedCell(element) {
    if (selectedCell) {
        if (fractionMode) {
            if (fractionUp) {
                if (!selectedCell.hasClass("fraction-cell"))
                    selectedCell.html(`<span>${$(element).text()}</span>⁄<sub></sub>`).addClass("fraction-cell");
                else
                    selectedCell.html(
                        selectedCell.html()
                            .replace(/(.*)<\/span>/,
                                `<span>$1${$(element).text()}</span>`));
            } else {
                selectedCell.html(
                    selectedCell.html()
                        .replace(/(.*)<\/sub>/,
                            `<sub>$1${$(element).text()}</sub>`));
            }
        } else {
            selectedCell.html($(element).clone().addClass("key-cloned"));
            selectedCell.addClass("filled-cell");

            let nextCell = getNextCell();
            if (getNextCell()) {
                flagCell(nextCell);
                if (rootMode) {
                    nextCell.addClass('rooted-cell');
                }
                if (divisionMode) {
                    nextCell.addClass('divided-cell');
                }
            }
        }
    }
}

function addKeysClickBehavior() {

    const $allKeys = $('ul.qwerty li a');

    addNormalKeysClickBehavior($allKeys);

    // indexing keys
    addIndexingKeysClickBehavior();

    // red special keys
    addSpecialKeysClickBehavior();

}

function addNormalKeysClickBehavior($allKeys) {
    $allKeys.unbind("click");
    $allKeys.click(function () {
        let previousFilledCell = getPreviousFilledCell();
        if (isIndexingMode(previousFilledCell)) {

            let keyValueWrapped = '' + $(this).text() + '';
            if (previousFilledCell.data("indexingDownApplied")) {
                keyValueWrapped = keyValueWrapped.replace('sup', 'sub');
            }
            let replaceValue = '$2' + keyValueWrapped + '<\/span>';

            if (previousFilledCell.data("indexingUpLeftApplied")) {
                replaceValue = '' + keyValueWrapped + '$2<\/span>';
            }
            if (previousFilledCell.data("rootIndexingApplied")) {
                replaceValue = '' + keyValueWrapped + '$2<\/span>';
            }
            previousFilledCell.html(
                previousFilledCell.html()
                    .replace(
                        /(.*)<\/span>/,
                        replaceValue
                    )
            );
        } else {
            copyKeyToSelectedCell(this);
        }
    });
}

function addSpecialKeysClickBehavior() {
    let specialKeys = ['a.delete-key', 'a.return-key', 'a.space-key'];
    $.each(specialKeys, function (i, v) { // unbind click event
        $(v).unbind("click");
    });

    // delete key
    $(specialKeys[0]).click(function () {
        deleteSelectedCell();
    });
    // return key
    $(specialKeys[1]).click(function () {
        returnSelectedCell();
    });
    // space key
    $(specialKeys[2]).click(function () {
        addSpaceCell();
    });
}

function addIndexingKeysClickBehavior() {
    let specialKeys = ['#repeater-key', '#degrees-key', '#indexingUpRight-key', '#indexingUpLeft-key',
        '#indexingDown-key', '#squareRoot-key', '#rootIndexing-key', '#longDivision-key', '#fractions-key'];
    $.each(specialKeys, function (i, v) { // unbind click event
        $(v).unbind("click");
    });

    // repeater key
    $(specialKeys[0]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        if (!previousFilledCell.data("repeaterApplied")) {
            previousFilledCell.html(
                previousFilledCell.html()
                    .replace(
                        /(.*)<\/span>/,
                        '$1.<\/span>'
                    )
            );
            previousFilledCell.data("repeaterApplied", true);
        }
    });

    // degrees key
    $(specialKeys[1]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        if (!previousFilledCell.data("degreesApplied")) {
            previousFilledCell.html(
                previousFilledCell.html()
                    .replace(
                        /(.*)<\/span>/,
                        '$1<\/span>'
                    )
            );
            previousFilledCell.data("degreesApplied", true);
        }
    });

    // indexingUpRightkey
    $(specialKeys[2]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        // toggle indexing mode for keyboards
        previousFilledCell.data("indexingUpRightApplied", !previousFilledCell.data("indexingUpRightApplied"));
    });

    // indexingUpLeft key
    $(specialKeys[3]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        previousFilledCell.data("indexingUpLeftApplied", !previousFilledCell.data("indexingUpLeftApplied"));
    });

    // indexingDown key
    $(specialKeys[4]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        previousFilledCell.data("indexingDownApplied", !previousFilledCell.data("indexingDownApplied"));
    });

    // squareRoot key
    $(specialKeys[5]).click(function () {
        rootMode = !rootMode;
        if (rootMode) {
            let element = $(this).clone();
            element.html(`<span class='root-span'>√<\/span><\/a>`);
            copyKeyToSelectedCell(element[0]);
        } else {
            getCurrentCell().removeClass('rooted-cell');
        }
    });

    // rootIndexing key
    $(specialKeys[6]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        previousFilledCell.data("rootIndexingApplied", !previousFilledCell.data("rootIndexingApplied"));
    });

    // longDivision key
    $(specialKeys[7]).click(function () {
        divisionMode = !divisionMode;
        if (divisionMode) {
            copyKeyToSelectedCell(this);
        } else {
            getCurrentCell().removeClass('divided-cell');
        }
    });

    // fractions key
    $(specialKeys[8]).click(function () {
        if (!fractionMode) {
            fractionMode = !fractionMode;
            fractionUp = true;
        } else {
            if (fractionUp) {
                fractionUp = false;
                fractionDown = true;
            }
            else if (fractionDown) {
                fractionDown = false;
                fractionMode = false;
                flagCell(getNextCell());
            }
            // copyKeyToSelectedCell(this);
        }
    });
}

<commit_msg>Refactor function<commit_after>$(document).ready(function () {

    drawGrid(0, 0);

    addKeysClickBehavior();

    $(window).resize(function () {
        drawGrid(0, 0);
    });

});

function addCellClickBehavior() {
    $("#grid td.cell").unbind("click");
    $("#grid td.cell").each(function () {
        $(this).click(function () {
            flagCell($(this));
        });
    });
}

function deleteSelectedCell() {
    if (selectedCell) {
        selectedCell.html("");
        selectedCell.removeClass("filled-cell rooted-cell divided-cell");
        flagCell(getPreviousFilledCell());
    }
}

function returnSelectedCell() {
    if (selectedCell.nextAll("td.cell:eq(" + (columnsNumber - 1) + ")")) {
        for (let j = CELL_SIDE; j <= $('#grid').width(); j += CELL_SIDE) {
            $('#grid').append("	");
            rowsNumber++;
        }
        addCellClickBehavior(); // flag current cell selected
        flagCell(selectedCell.nextAll("td.cell:eq(" + (columnsNumber - 1) + ")"));
    }

}

function addSpaceCell() {
    if (selectedCell.next("td.cell")) {
        flagCell(selectedCell.next("td.cell"));
    }
}

function copyKeyToSelectedCell(element) {
    if (selectedCell) {
        if (fractionMode) {
            if (fractionUp) {
                if (!selectedCell.hasClass("fraction-cell"))
                    selectedCell.html(`<span>${$(element).text()}</span>⁄<sub></sub>`).addClass("fraction-cell");
                else
                    selectedCell.html(
                        selectedCell.html()
                            .replace(/(.*)<\/span>/,
                                `<span>$1${$(element).text()}</span>`));
            } else {
                selectedCell.html(
                    selectedCell.html()
                        .replace(/(.*)<\/sub>/,
                            `<sub>$1${$(element).text()}</sub>`));
            }
        } else {
            selectedCell.html($(element).clone().addClass("key-cloned"));
            selectedCell.addClass("filled-cell");

            let nextCell = getNextCell();
            if (getNextCell()) {
                flagCell(nextCell);
                if (rootMode) {
                    nextCell.addClass('rooted-cell');
                }
                if (divisionMode) {
                    nextCell.addClass('divided-cell');
                }
            }
        }
    }
}

function addKeysClickBehavior() {

    const $allKeys = $('ul.qwerty li a');

    addNormalKeysClickBehavior($allKeys);

    // indexing keys
    addIndexingKeysClickBehavior();

    // red special keys
    addSpecialKeysClickBehavior();

    addTopBarButtonsClickBehavior();
}

function addNormalKeysClickBehavior($allKeys) {
    $allKeys.unbind("click");
    $allKeys.click(function () {
        let previousFilledCell = getPreviousFilledCell();
        if (isIndexingMode(previousFilledCell)) {

            let keyValueWrapped = '' + $(this).text() + '';
            if (previousFilledCell.data("indexingDownApplied")) {
                keyValueWrapped = keyValueWrapped.replace('sup', 'sub');
            }
            let replaceValue = '$2' + keyValueWrapped + '<\/span>';

            if (previousFilledCell.data("indexingUpLeftApplied")) {
                replaceValue = '' + keyValueWrapped + '$2<\/span>';
            }
            if (previousFilledCell.data("rootIndexingApplied")) {
                replaceValue = '' + keyValueWrapped + '$2<\/span>';
            }
            previousFilledCell.html(
                previousFilledCell.html()
                    .replace(
                        /(.*)<\/span>/,
                        replaceValue
                    )
            );
        } else {
            copyKeyToSelectedCell(this);
        }
    });
}

function addSpecialKeysClickBehavior() {
    let specialKeys = ['a.delete-key', 'a.return-key', 'a.space-key'];
    $.each(specialKeys, function (i, v) { // unbind click event
        $(v).unbind("click");
    });

    // delete key
    $(specialKeys[0]).click(function () {
        deleteSelectedCell();
    });
    // return key
    $(specialKeys[1]).click(function () {
        returnSelectedCell();
    });
    // space key
    $(specialKeys[2]).click(function () {
        addSpaceCell();
    });
}

function addIndexingKeysClickBehavior() {
    let specialKeys = ['#repeater-key', '#degrees-key', '#indexingUpRight-key', '#indexingUpLeft-key',
        '#indexingDown-key', '#squareRoot-key', '#rootIndexing-key', '#longDivision-key', '#fractions-key'];
    $.each(specialKeys, function (i, v) { // unbind click event
        $(v).unbind("click");
    });

    // repeater key
    $(specialKeys[0]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        if (!previousFilledCell.data("repeaterApplied")) {
            previousFilledCell.html(
                previousFilledCell.html()
                    .replace(
                        /(.*)<\/span>/,
                        '$1.<\/span>'
                    )
            );
            previousFilledCell.data("repeaterApplied", true);
        }
    });

    // degrees key
    $(specialKeys[1]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        if (!previousFilledCell.data("degreesApplied")) {
            previousFilledCell.html(
                previousFilledCell.html()
                    .replace(
                        /(.*)<\/span>/,
                        '$1<\/span>'
                    )
            );
            previousFilledCell.data("degreesApplied", true);
        }
    });

    // indexingUpRightkey
    $(specialKeys[2]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        // toggle indexing mode for keyboards
        previousFilledCell.data("indexingUpRightApplied", !previousFilledCell.data("indexingUpRightApplied"));
    });

    // indexingUpLeft key
    $(specialKeys[3]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        previousFilledCell.data("indexingUpLeftApplied", !previousFilledCell.data("indexingUpLeftApplied"));
    });

    // indexingDown key
    $(specialKeys[4]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        previousFilledCell.data("indexingDownApplied", !previousFilledCell.data("indexingDownApplied"));
    });

    // squareRoot key
    $(specialKeys[5]).click(function () {
        rootMode = !rootMode;
        if (rootMode) {
            let element = $(this).clone();
            element.html(`<span class='root-span'>√<\/span><\/a>`);
            copyKeyToSelectedCell(element[0]);
        } else {
            getCurrentCell().removeClass('rooted-cell');
        }
    });

    // rootIndexing key
    $(specialKeys[6]).click(function () {
        let previousFilledCell = getPreviousFilledCell();
        previousFilledCell.data("rootIndexingApplied", !previousFilledCell.data("rootIndexingApplied"));
    });

    // longDivision key
    $(specialKeys[7]).click(function () {
        divisionMode = !divisionMode;
        if (divisionMode) {
            copyKeyToSelectedCell(this);
        } else {
            getCurrentCell().removeClass('divided-cell');
        }
    });

    // fractions key
    $(specialKeys[8]).click(function () {
        if (!fractionMode) {
            fractionMode = !fractionMode;
            fractionUp = true;
        } else {
            if (fractionUp) {
                fractionUp = false;
                fractionDown = true;
            }
            else if (fractionDown) {
                fractionDown = false;
                fractionMode = false;
                flagCell(getNextCell());
            }
            // copyKeyToSelectedCell(this);
        }
    });
}

function addTopBarButtonsClickBehavior() {
    const CUT_BTN_INDEX = 9;
    const COPY_BTN_INDEX = 10;
    const PASTE_BTN_INDEX = 12;

    let btnSelector = ".bar-top button";

    $(btnSelector)[CUT_BTN_INDEX].click(function () {
        Operations.cut(getCurrentCell());
    });

    $(btnSelector)[COPY_BTN_INDEX].click(function () {
        Operations.copy(getCurrentCell());
    });

    $(btnSelector)[PASTE_BTN_INDEX].click(function () {
        Operations.paste(getCurrentCell());
    });
}
<|endoftext|>


<commit_before>    function scrollme(place){
if (location.pathname.replace(/^\//,'') == place.pathname.replace(/^\//,'') && location.hostname == place.hostname) {
                var target = $(place.hash);
                target = target.length ? target : $('[name=' + place.hash.slice(1) +']');
                if (target.length) {
                  $('html,body').animate({
                    scrollTop: target.offset().top
                  }, 1000);
                  return false;
                }
              }
            };
$(document).on('scroll touchmove touchend', function(e) {
  var offTop = $(document).scrollTop();
  $('#hero').find('h1').css({
    marginTop: - (offTop * 0.2),
    opacity: (100 - (offTop * 0.2)) / 100
  });
  $('#hero').find('p').css({
    marginTop: - (offTop * 0.05),
    opacity: (100 - (offTop * 0.2)) / 100
  });
});
<commit_msg>better fade<commit_after>    function scrollme(place){
if (location.pathname.replace(/^\//,'') == place.pathname.replace(/^\//,'') && location.hostname == place.hostname) {
                var target = $(place.hash);
                target = target.length ? target : $('[name=' + place.hash.slice(1) +']');
                if (target.length) {
                  $('html,body').animate({
                    scrollTop: target.offset().top
                  }, 1000);
                  return false;
                }
              }
            };
$(document).on('scroll touchmove touchend', function(e) {
  var offTop = $(document).scrollTop();
  $('#hero').find('h1').css({
    marginTop: - (offTop * -1),
    opacity: (100 - (offTop * 0.2)) / 100
  });
  $('#hero').find('p').css({
    marginTop: - (offTop * 0.05),
    opacity: (100 - (offTop * 0.2)) / 100
  });
});
<|endoftext|>


<commit_before>function updateHodgeDiamond(surface) {
  $("output#h01").text(surface.h01);
  $("output#h10").text(surface.h10);

  $("output#h20").text(surface.h20);
  $("output#h11").text(surface.h11);
  $("output#h02").text(surface.h02);

  $("output#h21").text(surface.h21);
  $("output#h12").text(surface.h12);
}

function updateInvariant(element, value) {
  // this is ugly, but the .text() contains a plaintext version, so we look for the first backslash indicating the actual start of the LaTeX...
  var latex = "\\" + element.text().split("\\").slice(1).join("\\");

  // the text between the first and second equals sign is what is changed
  var parts = latex.split("=");
  parts[1] = value;
  // remove the last $ if there is one (this could be prettier...)
  parts[parts.length - 1] = parts[parts.length - 1].trim();
  if (parts[parts.length - 1][parts[parts.length - 1].length - 1] == "$")
    parts[parts.length - 1] = parts[parts.length - 1].slice(0, -1);

  element.text("$" + parts.join("=") + "$");
}

function updateInvariants(surface) {
  updateInvariant($("dd#b1"), surface.b1);
  updateInvariant($("dd#b2"), surface.b2);
  updateInvariant($("dd#b3"), surface.b3);

  updateInvariant($("dd#e"), surface.e);

  updateInvariant($("dd#q"), surface.h01);

  updateInvariant($("dd#pg"), surface.h02);

  updateInvariant($("dd#pa"), surface.pa);

  updateInvariant($("dd#chi"), surface.chi);

  updateInvariant($("dd#tau"), surface.tau);

  updateInvariant($("dd#c2"), surface.c2);
  updateInvariant($("dd#c12"), surface.c12);

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}

d3.selection.prototype.moveToFront = function() {
  return this.each(function(){
    this.parentNode.appendChild(this);
  });
};

function setKodairaDimension(value) {
  if (value == -1)
    $("output#kodaira-output").text("$-\\infty$");
  else
    $("output#kodaira-output").text(value);

  var className = "kodaira-" + value;
  if (value == -1)
    className = "kodaira-infty";

  // make all nodes inactive
  d3.selectAll("circle")
    .classed("inactive", true);

  // make the nodes of the correct Kodaira dimension active
  var activeNodes = d3.selectAll("circle")
    .filter(function(d) { return d.kodaira == value; });
  activeNodes.classed("inactive", false);
  // SVG doesn't have a z-index so we change the order of elements
  activeNodes.moveToFront();

  // make the inequalities active if Kodaira dimension 2
  $("p.kodaira-2").toggleClass("inactive", value != 2);
  d3.selectAll("text.kodaira-2").classed("inactive", value != 2);

  // remove candidates
  clearCandidates();
  // make the Hodge diamond and invariants shaded
  setInactive();

  // indicate that no Chern numbers have been selected
  noSelectionMessage();

  // make all nodes inactive
  d3.selectAll("circle").classed("active", false);

  // destroy tooltips for all nodes
  $("[data-toggle='tooltip']").tooltip("destroy");
  // enable tooltips for currently active nodes
  $("[data-toggle='tooltip']:not(.inactive)").tooltip(tooltipConfig);
  $("[data-toggle='tooltip']").on("shown.bs.tooltip", function() {
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
  });

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}

// the state is the value for toggleClass to inactive
function toggleHodgeDiamond(state) {
  $("fieldset#diamond output:not(.constant)").toggleClass("inactive", state);

  // if the state is true it means we want to make the Hodge diamond inactive
  if (state)
    $("output#h01, output#h10, output#h02, output#h11, output#h20, output#h12, output#h21").text("?");
}

// the state is the value for toggleClass to inactive
function toggleInvariants(state) {
  $("fieldset#overview output").toggleClass("inactive", state);

  // if the state is true it means we want to make the invariants inactive
  if (state) {
    var invariants = ["b1", "b2", "b3", "e", "q", "pg", "pa", "chi", "tau", "c2", "c12"];

    for (var i = 0; i < invariants.length; i++)
      updateInvariant($("dd#" + invariants[i]), "{\\color{undefined-gray}{?}}");
  }
}

// clear candidates
function clearCandidates() {
  // remove the "no pair selected" message
  $("fieldset#candidates p").remove();

  // remove all children in the candidates list
  $("fieldset#candidates ol").empty();

  // remove the coordinates from the legend in the fieldset
  $("fieldset#candidates legend").text("Candidates");
}

// show that no selection of Chern numbers has been made
function noSelectionMessage() {
  $("fieldset#candidates").prepend("
No pair of Chern numbers selected.");
}

// add a surface to the candidates list
function addCandidateSurface(surface) {
  var link = $("" + surface.name + "").click(function(e) { loadSurface($(e.currentTarget).parent(), surface); });
  $("fieldset#candidates ol").append($("
").append(link));
}

// we make the Hodge diamond and the invariants inactive and empty, and reset the description
function setInactive() {
  toggleHodgeDiamond(true);
  toggleInvariants(true);

  $("fieldset#surface div").remove();
  $("fieldset#surface").append("

No surface selected.
");
}

// load the invariants of a surface
function loadSurface(element, surface) {
  // make the correct list element active
  $("fieldset#candidates li").removeClass("active");
  element.toggleClass("active", true);

  toggleHodgeDiamond(false);
  toggleInvariants(false);
  updateHodgeDiamond(surface);
  updateInvariants(surface);

  $("fieldset#surface div").remove();
  if ("description" in surface)
    $("fieldset#surface").append("
" + surface.description + "
");
  else
    $("fieldset#surface").append("

No description available.
");

  if ("construction" in surface)
    $("fieldset#surface div").append("
Construction
" + surface.construction);

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}
<commit_msg>Fixed weird bug in invariant update<commit_after>function updateHodgeDiamond(surface) {
  $("output#h01").text(surface.h01);
  $("output#h10").text(surface.h10);

  $("output#h20").text(surface.h20);
  $("output#h11").text(surface.h11);
  $("output#h02").text(surface.h02);

  $("output#h21").text(surface.h21);
  $("output#h12").text(surface.h12);
}

function updateInvariant(element, value) {
  // on the first run we save the LaTeX code for future use in a location that MathJax cannot mess with
  if (!element.data("latex"))
    element.data("latex", element.text());

  // the text between the first and second equals sign is what is changed
  var parts = element.data("latex").split("=");
  parts[1] = value;

  element.text(parts.join("="));
}

function updateInvariants(surface) {
  updateInvariant($("dd#b1"), surface.b1);
  updateInvariant($("dd#b2"), surface.b2);
  updateInvariant($("dd#b3"), surface.b3);

  updateInvariant($("dd#e"), surface.e);

  updateInvariant($("dd#q"), surface.h01);

  updateInvariant($("dd#pg"), surface.h02);

  updateInvariant($("dd#pa"), surface.pa);

  updateInvariant($("dd#chi"), surface.chi);

  updateInvariant($("dd#tau"), surface.tau);

  updateInvariant($("dd#c2"), surface.c2);
  updateInvariant($("dd#c12"), surface.c12);

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}

d3.selection.prototype.moveToFront = function() {
  return this.each(function(){
    this.parentNode.appendChild(this);
  });
};

function setKodairaDimension(value) {
  if (value == -1)
    $("output#kodaira-output").text("$-\\infty$");
  else
    $("output#kodaira-output").text(value);

  var className = "kodaira-" + value;
  if (value == -1)
    className = "kodaira-infty";

  // make all nodes inactive
  d3.selectAll("circle")
    .classed("inactive", true);

  // make the nodes of the correct Kodaira dimension active
  var activeNodes = d3.selectAll("circle")
    .filter(function(d) { return d.kodaira == value; });
  activeNodes.classed("inactive", false);
  // SVG doesn't have a z-index so we change the order of elements
  activeNodes.moveToFront();

  // make the inequalities active if Kodaira dimension 2
  $("p.kodaira-2").toggleClass("inactive", value != 2);
  d3.selectAll("text.kodaira-2").classed("inactive", value != 2);

  // remove candidates
  clearCandidates();
  // make the Hodge diamond and invariants shaded
  setInactive();

  // indicate that no Chern numbers have been selected
  noSelectionMessage();

  // make all nodes inactive
  d3.selectAll("circle").classed("active", false);

  // destroy tooltips for all nodes
  $("[data-toggle='tooltip']").tooltip("destroy");
  // enable tooltips for currently active nodes
  $("[data-toggle='tooltip']:not(.inactive)").tooltip(tooltipConfig);
  $("[data-toggle='tooltip']").on("shown.bs.tooltip", function() {
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
  });

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}

// the state is the value for toggleClass to inactive
function toggleHodgeDiamond(state) {
  $("fieldset#diamond output:not(.constant)").toggleClass("inactive", state);

  // if the state is true it means we want to make the Hodge diamond inactive
  if (state)
    $("output#h01, output#h10, output#h02, output#h11, output#h20, output#h12, output#h21").text("?");
}

// the state is the value for toggleClass to inactive
function toggleInvariants(state) {
  $("fieldset#overview output").toggleClass("inactive", state);

  // if the state is true it means we want to make the invariants inactive
  if (state) {
    var invariants = ["b1", "b2", "b3", "e", "q", "pg", "pa", "chi", "tau", "c2", "c12"];

    for (var i = 0; i < invariants.length; i++)
      updateInvariant($("dd#" + invariants[i]), "{\\color{undefined-gray}{?}}");
  }
}

// clear candidates
function clearCandidates() {
  // remove the "no pair selected" message
  $("fieldset#candidates p").remove();

  // remove all children in the candidates list
  $("fieldset#candidates ol").empty();

  // remove the coordinates from the legend in the fieldset
  $("fieldset#candidates legend").text("Candidates");
}

// show that no selection of Chern numbers has been made
function noSelectionMessage() {
  $("fieldset#candidates").prepend("
No pair of Chern numbers selected.");
}

// add a surface to the candidates list
function addCandidateSurface(surface) {
  var link = $("" + surface.name + "").click(function(e) { loadSurface($(e.currentTarget).parent(), surface); });
  $("fieldset#candidates ol").append($("
").append(link));
}

// we make the Hodge diamond and the invariants inactive and empty, and reset the description
function setInactive() {
  toggleHodgeDiamond(true);
  toggleInvariants(true);

  $("fieldset#surface div").remove();
  $("fieldset#surface").append("

No surface selected.
");
}

// load the invariants of a surface
function loadSurface(element, surface) {
  // make the correct list element active
  $("fieldset#candidates li").removeClass("active");
  element.toggleClass("active", true);

  toggleHodgeDiamond(false);
  toggleInvariants(false);
  updateHodgeDiamond(surface);
  updateInvariants(surface);

  $("fieldset#surface div").remove();
  if ("description" in surface)
    $("fieldset#surface").append("
" + surface.description + "
");
  else
    $("fieldset#surface").append("

No description available.
");

  if ("construction" in surface)
    $("fieldset#surface div").append("
Construction
" + surface.construction);

  MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
}
<|endoftext|>


<commit_before>(function(Cortana) {
	'use strict';

	var Game = function(canvas, width, height) {
		var self = this;
		this.config = null;
		this.canvas = canvas;
		this.width = width;
		this.height = height;
		this.isRunning = false;
		this.isPaused = false;
		this.time = 0;
		this.frameId = null;

		this.entities = [];

		this.input = null;
		this.timer = null;
		this.render = null;

		this.isLoaded = false;
		this.debug = true;

		this.scenes = [];

		this.init();

		return this;
	}

	Game.prototype = {

		init: function() {
			var c = document.getElementById(this.canvas);
			c.setAttribute('width', this.width + 'px');
			c.setAttribute('height', this.height + 'px');

			Cortana.canvas = this.canvas;
			this.context = document.getElementById(Cortana.canvas).getContext('2d');

			Cortana.width = this.width;
			Cortana.height = this.height;

			this.input = new Cortana.Input(this);
			this.timer = new Cortana.Timer(this);
			this.render = new Cortana.Render(this);
			this.loader = new Cortana.Loader(this);

			this.isLoaded = true;
		},

		start: function() {
			if (this.isLoaded) {
				this.timer.start();
			}
		},

		reset: function() {
		},

		update: function(dt) {

			// Clear canvas
			var canvas = document.getElementById(Cortana.canvas);
			var context = document.getElementById(Cortana.canvas).getContext('2d');

			context.save();

			// Use the identity matrix while clearing the canvas
			context.setTransform(1, 0, 0, 1, 0, 0);
			context.clearRect(0, 0, canvas.width, canvas.height);

			// Restore the transform
			context.restore();

			// Update entities

			for (var e = 0; e < this.entities.length; e++) {
				if (this.entities[e].remove) {
					this.entities.splice(e, 1);
				}
				this.entities[e].update(dt);
			}

			this.checkEntities();

			for (var s = 0, slen = this.scenes.length; s < slen; s++) {
				this.scenes[s](dt);
			}
		},

		add: function(entity) {
			// var entity = new Cortana.Entity(e);
			var next_index  = this.entities.length + 1;
			entity.id = next_index;

			var ent_id = this.entities.push(entity);
			this.entities.indexOf(entity);

			this.entities.sort(function(a, b) {
				return a.zIndex - b.zIndex;
			});

			return this.entities.indexOf(entity);
		},

		checkEntities: function() {
			for (var e = 0, elen = this.entities.length; e < elen; e++) {
				var thisEntity = this.getEntityById(e);

				if (!thisEntity.canCollide) continue;

				for (var o = e + 1; o < elen; o++) {
					var thatEntity = this.getEntityById(o);

					if (!thatEntity.canCollide) continue;

					if (thisEntity.touches(thatEntity)) {
						if (thisEntity.name === thatEntity.collisionCheck) {
							thatEntity.handleCollision(thisEntity);
						}

						if (thisEntity.collisionCheck === thatEntity.name) {
							thisEntity.handleCollision(thatEntity);
						}
					}
				}
			}
		},

		getEntityById: function(id) {
			return this.entities[id];
		},

		getEntitiesByName: function(name) {
			var found = [];

			for (var e in this.entities) {
				if (this.entities[e].name === name) {
					found.push(this.entities[e]);
				}
			}

			return found;
		},

		addScene: function(scene) {
			this.scenes.push(scene);
		}

	}

	Game.prototype.constructor = Game;
	Cortana.Game = Game;
}(Cortana));<commit_msg>take out entity creation from game.js<commit_after>(function(Cortana) {
	'use strict';

	var Game = function(canvas, width, height) {
		var self = this;
		this.config = null;
		this.canvas = canvas;
		this.width = width;
		this.height = height;
		this.isRunning = false;
		this.isPaused = false;
		this.time = 0;
		this.frameId = null;

		this.entities = [];

		this.input = null;
		this.timer = null;
		this.render = null;

		this.isLoaded = false;
		this.debug = true;

		this.scenes = [];

		this.init();

		return this;
	}

	Game.prototype = {

		init: function() {
			var c = document.getElementById(this.canvas);
			c.setAttribute('width', this.width + 'px');
			c.setAttribute('height', this.height + 'px');

			Cortana.canvas = this.canvas;
			this.context = document.getElementById(Cortana.canvas).getContext('2d');

			Cortana.width = this.width;
			Cortana.height = this.height;

			this.input = new Cortana.Input(this);
			this.timer = new Cortana.Timer(this);
			this.render = new Cortana.Render(this);
			this.loader = new Cortana.Loader(this);

			this.isLoaded = true;
		},

		start: function() {
			if (this.isLoaded) {
				this.timer.start();
			}
		},

		reset: function() {
		},

		update: function(dt) {

			// Clear canvas
			var canvas = document.getElementById(Cortana.canvas);
			var context = document.getElementById(Cortana.canvas).getContext('2d');

			context.save();

			// Use the identity matrix while clearing the canvas
			context.setTransform(1, 0, 0, 1, 0, 0);
			context.clearRect(0, 0, canvas.width, canvas.height);

			// Restore the transform
			context.restore();

			// Update entities

			for (var e = 0; e < this.entities.length; e++) {
				if (this.entities[e].remove) {
					this.entities.splice(e, 1);
				}
				this.entities[e].update(dt);
			}

			this.checkEntities();

			for (var s = 0, slen = this.scenes.length; s < slen; s++) {
				this.scenes[s](dt);
			}
		},

		add: function(entity) {
			var next_index  = this.entities.length + 1;
			entity.id = next_index;

			var ent_id = this.entities.push(entity);
			this.entities.indexOf(entity);

			this.entities.sort(function(a, b) {
				return a.zIndex - b.zIndex;
			});

			return this.entities.indexOf(entity);
		},

		checkEntities: function() {
			for (var e = 0, elen = this.entities.length; e < elen; e++) {
				var thisEntity = this.getEntityById(e);

				if (!thisEntity.canCollide) continue;

				for (var o = e + 1; o < elen; o++) {
					var thatEntity = this.getEntityById(o);

					if (!thatEntity.canCollide) continue;

					if (thisEntity.touches(thatEntity)) {
						if (thisEntity.name === thatEntity.collisionCheck) {
							thatEntity.handleCollision(thisEntity);
						}

						if (thisEntity.collisionCheck === thatEntity.name) {
							thisEntity.handleCollision(thatEntity);
						}
					}
				}
			}
		},

		getEntityById: function(id) {
			return this.entities[id];
		},

		getEntitiesByName: function(name) {
			var found = [];

			for (var e in this.entities) {
				if (this.entities[e].name === name) {
					found.push(this.entities[e]);
				}
			}

			return found;
		},

		addScene: function(scene) {
			this.scenes.push(scene);
		}

	}

	Game.prototype.constructor = Game;
	Cortana.Game = Game;
}(Cortana));<|endoftext|>


<commit_before>"use strict";

var scene, renderer, graphManager;
var cPlanes = {};
var nickname;

function startGame(name)
{
	nickname = name;
	floatingManager.stop();
	$("#overlays").remove();
	$("#canvas").remove();
	$("#hud").show();

	renderer = new THREE.WebGLRenderer();
	renderer.domElement.setAttribute("id", "game");
	renderer.setSize(window.innerWidth, window.innerHeight-$("#hud").innerHeight());
	renderer.setClearColor(0xadd8e6);

	scene = new THREE.Scene();
	var cube = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshNormalMaterial());
	scene.add(cube);

	var light = new THREE.AmbientLight(0xffffff, 1);
	scene.add(light);
	window.backend.joinGame(nickname);
	graphManager = new GraphManager("graph-overlay");
	graphManager.addGraph("position");
	graphManager.addGraph("velocity");
	graphManager.addGraph("acceleration");

	document.addEventListener("keydown", function(e){
		if(e.keyCode == 38){
			cPlanes[window.backend.id].move("z", 1);

		} else if(e.keyCode == 40){
			cPlanes[window.backend.id].move("z", -1);
		} else if(e.keyCode == 37){
			//cPlanes[window.backend.id].move("x", -1);
			cPlanes[window.backend.id].setRotation(Math.PI,cPlanes[window.backend.id].dae.rotation.y-Math.PI/32,0);
		} else if(e.keyCode == 39){
			//cPlanes[window.backend.id].move("x", 1);
			cPlanes[window.backend.id].setRotation(Math.PI,cPlanes[window.backend.id].dae.rotation.y+Math.PI/32,0);
		} else if(e.keyCode == 87){
			cPlanes[window.backend.id].move("y", 1);
		} else if(e.keyCode == 83){
			cPlanes[window.backend.id].move("y", -1);
		}
		if(e.keyCode == 32){
			cPlanes[window.backend.id].shoot();
		}
	});
	document.addEventListener("keyup", function(e){
		cPlanes[window.backend.id].setSpeed(0,0,0);
		//cPlanes[window.backend.id].setRotation(Math.PI,0,0);
	});

}

function render(){
	if(cPlanes[window.backend.id]){
		cPlanes[window.backend.id].graphDraw();
		renderer.render(scene, cPlanes[window.backend.id].camera);
	}
	requestAnimationFrame(render);
}

function loadPlane(uuid, nickname, model, posX, posY, posZ)
{
	var dae;
	var loader = new THREE.ColladaLoader();
	var plane;
	loader.load("models/"+model+"/model.dae", function(collada)
	{
		dae = collada.scene;
		dae.scale.x=dae.scale.y=dae.scale.z=1;
		dae.rotation.x=Math.PI;
		dae.updateMatrix();
		if(uuid == window.backend.id){
			render();
			dae.visible = false;
		}
		plane = new Plane(posX, posY, posZ, dae, 4 /*rotation not used right now*/, 0.05, nickname);
		if(cPlanes[uuid] == undefined){
			cPlanes[uuid] = plane;
			cPlanes[uuid].draw();
			cPlanes[uuid].render();
		}
  });
}
<commit_msg>more cubes<commit_after>"use strict";

var scene, renderer, graphManager;
var cPlanes = {};
var nickname;

function startGame(name)
{
	nickname = name;
	floatingManager.stop();
	$("#overlays").remove();
	$("#canvas").remove();
	$("#hud").show();

	renderer = new THREE.WebGLRenderer();
	renderer.domElement.setAttribute("id", "game");
	renderer.setSize(window.innerWidth, window.innerHeight-$("#hud").innerHeight());
	renderer.setClearColor(0xadd8e6);

	scene = new THREE.Scene();
	var cube = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshNormalMaterial());
	for(var i = 0; i < 10; i++){
	    for(var j = 0; i < 10; i++){
	    	cube.position.x = i*11;
	    	cube.position.z = i*11;
		scene.add(cube);
	    }
	}

	var light = new THREE.AmbientLight(0xffffff, 1);
	scene.add(light);
	window.backend.joinGame(nickname);
	graphManager = new GraphManager("graph-overlay");
	graphManager.addGraph("position");
	graphManager.addGraph("velocity");
	graphManager.addGraph("acceleration");

	document.addEventListener("keydown", function(e){
		if(e.keyCode == 38){
			cPlanes[window.backend.id].move("z", 1);

		} else if(e.keyCode == 40){
			cPlanes[window.backend.id].move("z", -1);
		} else if(e.keyCode == 37){
			//cPlanes[window.backend.id].move("x", -1);
			cPlanes[window.backend.id].setRotation(Math.PI,cPlanes[window.backend.id].dae.rotation.y-Math.PI/32,0);
		} else if(e.keyCode == 39){
			//cPlanes[window.backend.id].move("x", 1);
			cPlanes[window.backend.id].setRotation(Math.PI,cPlanes[window.backend.id].dae.rotation.y+Math.PI/32,0);
		} else if(e.keyCode == 87){
			cPlanes[window.backend.id].move("y", 1);
		} else if(e.keyCode == 83){
			cPlanes[window.backend.id].move("y", -1);
		}
		if(e.keyCode == 32){
			cPlanes[window.backend.id].shoot();
		}
	});
	document.addEventListener("keyup", function(e){
		cPlanes[window.backend.id].setSpeed(0,0,0);
		//cPlanes[window.backend.id].setRotation(Math.PI,0,0);
	});

}

function render(){
	if(cPlanes[window.backend.id]){
		cPlanes[window.backend.id].graphDraw();
		renderer.render(scene, cPlanes[window.backend.id].camera);
	}
	requestAnimationFrame(render);
}

function loadPlane(uuid, nickname, model, posX, posY, posZ)
{
	var dae;
	var loader = new THREE.ColladaLoader();
	var plane;
	loader.load("models/"+model+"/model.dae", function(collada)
	{
		dae = collada.scene;
		dae.scale.x=dae.scale.y=dae.scale.z=1;
		dae.rotation.x=Math.PI;
		dae.updateMatrix();
		if(uuid == window.backend.id){
			render();
			dae.visible = false;
		}
		plane = new Plane(posX, posY, posZ, dae, 4 /*rotation not used right now*/, 0.05, nickname);
		if(cPlanes[uuid] == undefined){
			cPlanes[uuid] = plane;
			cPlanes[uuid].draw();
			cPlanes[uuid].render();
		}
  });
}
<|endoftext|>


<commit_before>var language;
var category;
var word;
var imageCounter = 1;

$(document).ready(function()
	{
		startDiv=document.getElementById('start');
		prepareDiv=document.getElementById('prepare');
		prepareDiv.style.display= 'none';
		gameDiv=document.getElementById('gameArea');
		gameDiv.style.display= 'none';

		$("#image1")
		.css("right","0")
		for (var i = 2; i <= 7 ; i++) {
			$("#image"+i)
			.css("display","none")
			.css("right","0")
		}

		$("#start button")
		.hover(function(){
			$(this)
			.animate({width: "25%", height:"33%"}, 300)
		},function(){
			$(this)
			.animate({width: "23%", height:"30%"}, 300)
		})

		$("#but1")
		.click(function(){
			language = "tr";
			startDiv.style.display="none";
			prepareDiv.style.display= 'block';

			$("body")
			.css("background-color","66FFCC")

		})

		$("#but2")
		.click(function(){
			language ="eng";
			startDiv.style.display="none";
			prepareDiv.style.display= 'block';

			$("body")
			.css("background-color","66FFCC")

			$("#select")
			.html("Please select a category")

			$("#newGame")
			.html("New Game")
			selects = ["Animal", "City", "Goods", "Country", "Plant"]
			for (var i = 1; i < 6; i++) {
				$("#b"+i)
				.html(selects[i-1])
			};
		})

		$("#prepare button")
		.hover(function(){
			$(this)
			.animate({width: "11%", height:"9%"}, 100)
		},function(){
			$(this)
			.animate({width: "10%", height:"7%"}, 100)
		})
		.click(function(){
			category = $(this).html();
			if (category=="Hayvan" || category=="Animal") {
				word = animal();
			}else if (category=="Şehir"|| category=="City") {
				word = city();
			}else if (category=="Eşya"|| category=="Goods") {
				word = goods();
			}else if (category=="Ülke"|| category=="Country") {
				word = country();
			}else if (category=="Bitki"|| category=="Plant") {
				word = plant();
			}
			for (var i = 1; i <= word.length; i++) {
				$("#h"+i)
				.css("background-color","blue")
				.css("color","yellow")
				.css("width","80px")
				.css("height","80px")
				.css("font-size","40px")
				.css("font-weight","bold")
				.css("text-align","center")
				.css("padding-top","30px")
				.css("display","block")
			}

			prepareDiv.style.display= 'none';
			inputObject=document.getElementById('letter');
			if (language=="tr") {
				inputObject.placeholder = "Harf giriniz.";
				$("#gameText")
				.html("Bir " + category)
				$("#entered")
				.html("Girilen harfler: ")
			}
			else{
				inputObject.placeholder = "Enter a letter";
				$("#entered")
				.html("Entered letters: ")
				if (category=="Animal") {
					$("#gameText")
					.html("An " + category)
				}
				else{
					$("#gameText")
					.html("A " + category)
				}
			}
			gameArea.style.display = "block";
		})

		$("#footer img")
		.hover(function(){
			$(this)
			.animate({width: "40px", height:"40px"}, 150)
		},function(){
			$(this)
			.animate({width: "30px", height:"30px"}, 150)
		})

		$("#newGame")
		.click(function(){
			gameDiv.style.display= 'none';
			prepareDiv.style.display="block";
		})

		$("#letter")
		.keyup(function(){
			letter = $(this).val();
			document.getElementById('letter').value="";
			evaluate(letter);
		})

		function evaluate(l){
			flag = false;
			if (l.length>1) {
				if (language=="tr")
					alert("Lütfen sadece harf giriniz. Ve boş girmeyiniz")
				else
					alert("Please enter a letter");
			}
			if (!isLetter(l)) {
				if (language=="tr")
					alert("Lütfen sadece harf giriniz. Ve boş girmeyiniz")
				else
					alert("Please enter a letter");
			}
			else{
				for (var i = 1; i <= word.length; i++) {
					if (word[i-1] == l || word[i-1] == l.toUpperCase()) {
						$("#h"+i)
						.html(l);
						flag=true;
					};
				}
				if (!flag) { //harf yoksa
					var textP = document.getElementById('entered');
					textP.innerHTML = textP.innerHTML + "  " +l;
					$("#image"+imageCounter)
					.css("display","none")
					imageCounter++;
					$("#images")
					.css("text-align","right")
					$("#image"+imageCounter)
					.css("display","inline-block")
					if (imageCounter==7) {
						gameover();
					};
				}else { //harf varsa
					var end = true;
					for (var i = 1; i <= word.length; i++) {
						var divLetter = document.getElementById('h'+i).innerHTML;
						if (divLetter.length==0) {
							end = false;
						}
					}
					if (end) {
						won();
					};
				}
			}
		}
		function won(){
			if (language=="tr")
				swal("İyi iş!", "Tebrikler", "success")
			else
				swal("Good job!", "Congratulations", "success")
			resetGame();
		}
		function gameover(){
			if (language=="tr")
				sweetAlert("Oyun Bitti", "Kelime: "+ word, "error");
			else
				sweetAlert("Game Over", "The word: "+ word, "error");
			resetGame();
		}
		function resetGame(){
			imageCounter = 1;
			$("#entered")
			.html("")
			$("#image1")
				.css("display","block")
			for (var i = 2; i <= 7 ; i++) {
				$("#image"+i)
				.css("display","none")
			}
			for (var i = 1; i <= 10; i++) {
				$("#h"+i)
				.html("")
				.css("display","none");
			}
			gameDiv.style.display= 'none';
			prepareDiv.style.display="block";
		}
		function isLetter(char){	//harf girip girmediğini kontrol eden fonksiyon
			if(char=="") return true;
			var letter_pattern = /^[a-züöçğşıİÜĞÇŞÖ\s]+$/i;
			var ok = letter_pattern.test(char);
		    if (ok)
		        return true;
		    else
		        return false;
		}
	})

function city(){
	if (language=="tr") {
		array = ["İstanbul", "Eskişehir", "Ankara", "Kayseri", "Trabzon", "Bursa", "Çankırı",
		"Sinop", "Antalya", "Mersin", "İzmir", "Muğla", "Aydın", "Hakkari", "Rize", "Balıkesir",
		"Çanakkale", "Yalova", "Samsun", "Erzincan", "Erzurum", "Karabük", "Bartın", "Denizli",
		"Diyarbakır", "Adana", "Adıyaman", "Afyon", "Malatya", "Manisa"];
	}
	else{
		array = ["London", "istanbul", "Moscow", "Paris", "Manchester", "Madrid", "Barcelona",
		"Athenian", "Berlin", "Pekin", "Shanghai", "Karachi", "Beijing", "Delhi", "Milano", "Tianjin",
		"Amsterdam", "Mumbai", "Bern", "Rome", "Shenzhen", "Tokyo", "Bangkok", "Singapore", "Yokohama",
		"Santiago", "Liverpool", "Poznan", "Lyon", "Frankfurt"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function animal(){
	if (language=="tr") {
		array = ["penguen", "panda", "kırlangıç", "bukalemun", "zürafa", "papağan", "zebra",
		"ördek", "kartal", "salyangoz", "maymun", "balina", "panter", "kaplan", "geyik", "kanarya",
		"kertenkele", "karınca", "köpek", "sinek", "pire", "şahin", "eşek", "domuz", "keçi",
		"akbaba", "koyun", "tilki", "ceylan", "çakal"];
	}
	else{
		array = ["penguin", "panda", "swallow", "chameleon", "giraffe", "parrot", "zebra",
		"duck", "eagle", "snails", "monkey", "whale", "panther", "tiger", "deer", "canary",
		"lizard", "ant", "dog", "fly", "flea", "hawk", "donkey", "pork", "goat",
		"vulture", "sheep", "fox", "gazelle", "coyote"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function goods(){
	if (language=="tr") {
		array = ["masa", "sandalye", "kanepe", "askı", "vazo" , "bavul", "süpürge", "pantolon",
		"bilgisayar", "halı", "lamba", "şemsiye", "sehpa", "koltuk", "minder", "avize", "tencere"
		, "ranza", "sürahi", "çaydanlık" , "bardak" , "peçete" , "havlu" , "bornoz" ,"perde"
		, "kaşık", "çatal", "bıçak", "kumanda", "fırın"];
	}
	else{
		array = ["table", "chair", "couch", "hanger", "vase", "suitcase", "broom", "pants"
		, "computer", "carpet", "lamp", "umbrella", "stand", "seat", "cushion", "chandelier", "pot",
		"bunk", "pitcher", "teapot", "cup", "napkin", "towel", "bathrobe", "curtain",
		"spoon", "fork", "knife", "command", "oven"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function country(){
	if (language=="tr") {
		array = ["Türkiye", "Amerika", "İngiltere", "İspanya", "Fransa", "Almanya", "İsveç", "Arjantin",
			"Brezilya", "Rusya", "Litvanya", "Yunanistan", "Şili", "Portekiz", "Danimarka", "Macaristan",
			"Belçika", "Avusturya", "Venezuela", "Irak", "Gana", "Gürcistan", "Paraguay",
			"Japonya", "Hollanda", "Azerbeycan", "Pakistan", "Suriye", "Romanya", "Moldova"];
	}
	else{
		array =["Turkey", "America", "England", "Spain", "France", "Germany", "Sweden", "Argentina",
			"Brasil", "Russia", "Lithuania", "Greece", "Chile", "Portugal", "Denmark", "Hungary",
			"Belgium", "Austria", "Venezuela", "Iraq", "Ghana", "Georgia", "Paraguay",
			"Japan", "Kenya", "Azerbaijan", "Pakistan", "Syria", "Romania", "Moldova"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function plant(){
	if (language=="tr") {
		array = ["nane", "kekik", "papatya", "roka", "maydanoz", "marul", "lale", "kardelen",
			"dereotu", "fesleğen", "ıspanak", "pırasa", "lahana", "karnıbahar", "brokoli",
			"domates", "biber", "patlıcan", "avokado", "ananas", "armut", "portakal", "greyfurt",
			 "kestane", "kivi", "kiraz", "karpuz", "şalgam", "haşhaş", "kereviz"];
	}
	else{
		array = ["mint", "thyme", "daisy", "arugula", "parsley", "lettuce", "tulip", "snowdrop",
		"dill", "basil", "spinach", "leek", "cabbage", "cauliflower", "broccoli",
		"tomatoes", "pepper", "aubergine", "avocado", "pineapple", "pear", "orange", "grapefruit",
		"chestnut", "kiwi", "cherry", "watermelon", "turnip", "poppy", "celery"];
	}
	return array[Math.floor(Math.random() * 30)];
}
	<commit_msg>css array updated<commit_after>var language;
var category;
var word;
var imageCounter = 1;

$(document).ready(function()
	{
		startDiv=document.getElementById('start');
		prepareDiv=document.getElementById('prepare');
		prepareDiv.style.display= 'none';
		gameDiv=document.getElementById('gameArea');
		gameDiv.style.display= 'none';

		$("#image1")
		.css("right","0")
		for (var i = 2; i <= 7 ; i++) {
			$("#image"+i)
			.css({
				"display":"none",
				"right":"0"
			})
		}

		$("#start button")
		.hover(function(){
			$(this)
			.animate({width: "25%", height:"33%"}, 300)
		},function(){
			$(this)
			.animate({width: "23%", height:"30%"}, 300)
		})

		$("#but1")
		.click(function(){
			language = "tr";
			startDiv.style.display="none";
			prepareDiv.style.display= 'block';

			$("body")
			.css("background-color","66FFCC")

		})

		$("#but2")
		.click(function(){
			language ="eng";
			startDiv.style.display="none";
			prepareDiv.style.display= 'block';

			$("body")
			.css("background-color","66FFCC")

			$("#select")
			.html("Please select a category")

			$("#newGame")
			.html("New Game")
			selects = ["Animal", "City", "Goods", "Country", "Plant"]
			for (var i = 1; i < 6; i++) {
				$("#b"+i)
				.html(selects[i-1])
			};
		})

		$("#prepare button")
		.hover(function(){
			$(this)
			.animate({width: "11%", height:"9%"}, 100)
		},function(){
			$(this)
			.animate({width: "10%", height:"7%"}, 100)
		})
		.click(function(){
			category = $(this).html();
			if (category=="Hayvan" || category=="Animal") {
				word = animal();
			}else if (category=="Şehir"|| category=="City") {
				word = city();
			}else if (category=="Eşya"|| category=="Goods") {
				word = goods();
			}else if (category=="Ülke"|| category=="Country") {
				word = country();
			}else if (category=="Bitki"|| category=="Plant") {
				word = plant();
			}
			for (var i = 1; i <= word.length; i++) {
				$("#h"+i)
				.css({ 'background-color': "blue",
		            "color": "yellow",
					"width": "80px",
					"height": "80px",
					"font-size": "40px",
					"font-weight": "bold",
					"text-align": "center",
					"padding-top": "30px",
					"display": "block"
			     })
		}
			prepareDiv.style.display= 'none';
			inputObject=document.getElementById('letter');
			if (language=="tr") {
				inputObject.placeholder = "Harf giriniz.";
				$("#gameText")
				.html("Bir " + category)
				$("#entered")
				.html("Girilen harfler: ")
			}
			else{
				inputObject.placeholder = "Enter a letter";
				$("#entered")
				.html("Entered letters: ")
				if (category=="Animal") {
					$("#gameText")
					.html("An " + category)
				}
				else{
					$("#gameText")
					.html("A " + category)
				}
			}
			gameArea.style.display = "block";
		})

		$("#footer img")
		.hover(function(){
			$(this)
			.animate({width: "40px", height:"40px"}, 150)
		},function(){
			$(this)
			.animate({width: "30px", height:"30px"}, 150)
		})

		$("#newGame")
		.click(function(){
			gameDiv.style.display= 'none';
			prepareDiv.style.display="block";
		})

		$("#letter")
		.keyup(function(){
			letter = $(this).val();
			document.getElementById('letter').value="";
			evaluate(letter);
		})

		function evaluate(l){
			flag = false;
			if (l.length>1) {
				if (language=="tr")
					alert("Lütfen sadece harf giriniz. Ve boş girmeyiniz")
				else
					alert("Please enter a letter");
			}
			if (!isLetter(l)) {
				if (language=="tr")
					alert("Lütfen sadece harf giriniz. Ve boş girmeyiniz")
				else
					alert("Please enter a letter");
			}
			else{
				for (var i = 1; i <= word.length; i++) {
					if (word[i-1] == l || word[i-1] == l.toUpperCase()) {
						$("#h"+i)
						.html(l);
						flag=true;
					};
				}
				if (!flag) { //harf yoksa
					var textP = document.getElementById('entered');
					textP.innerHTML = textP.innerHTML + "  " +l;
					$("#image"+imageCounter)
					.css("display","none")
					imageCounter++;
					$("#images")
					.css("text-align","right")
					$("#image"+imageCounter)
					.css("display","inline-block")
					if (imageCounter==7) {
						gameover();
					};
				}else { //harf varsa
					var end = true;
					for (var i = 1; i <= word.length; i++) {
						var divLetter = document.getElementById('h'+i).innerHTML;
						if (divLetter.length==0) {
							end = false;
						}
					}
					if (end) {
						won();
					};
				}
			}
		}
		function won(){
			if (language=="tr")
				swal("İyi iş!", "Tebrikler", "success")
			else
				swal("Good job!", "Congratulations", "success")
			resetGame();
		}
		function gameover(){
			if (language=="tr")
				sweetAlert("Oyun Bitti", "Kelime: "+ word, "error");
			else
				sweetAlert("Game Over", "The word: "+ word, "error");
			resetGame();
		}
		function resetGame(){
			imageCounter = 1;
			$("#entered")
			.html("")
			$("#image1")
				.css("display","block")
			for (var i = 2; i <= 7 ; i++) {
				$("#image"+i)
				.css("display","none")
			}
			for (var i = 1; i <= 10; i++) {
				$("#h"+i)
				.html("")
				.css("display","none");
			}
			gameDiv.style.display= 'none';
			prepareDiv.style.display="block";
		}
		function isLetter(char){	//harf girip girmediğini kontrol eden fonksiyon
			if(char=="") return true;
			var letter_pattern = /^[a-züöçğşıİÜĞÇŞÖ\s]+$/i;
			var ok = letter_pattern.test(char);
		    if (ok)
		        return true;
		    else
		        return false;
		}
	})

function city(){
	if (language=="tr") {
		array = ["İstanbul", "Eskişehir", "Ankara", "Kayseri", "Trabzon", "Bursa", "Çankırı",
		"Sinop", "Antalya", "Mersin", "İzmir", "Muğla", "Aydın", "Hakkari", "Rize", "Balıkesir",
		"Çanakkale", "Yalova", "Samsun", "Erzincan", "Erzurum", "Karabük", "Bartın", "Denizli",
		"Diyarbakır", "Adana", "Adıyaman", "Afyon", "Malatya", "Manisa"];
	}
	else{
		array = ["London", "istanbul", "Moscow", "Paris", "Manchester", "Madrid", "Barcelona",
		"Athenian", "Berlin", "Pekin", "Shanghai", "Karachi", "Beijing", "Delhi", "Milano", "Tianjin",
		"Amsterdam", "Mumbai", "Bern", "Rome", "Shenzhen", "Tokyo", "Bangkok", "Singapore", "Yokohama",
		"Santiago", "Liverpool", "Poznan", "Lyon", "Frankfurt"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function animal(){
	if (language=="tr") {
		array = ["penguen", "panda", "kırlangıç", "bukalemun", "zürafa", "papağan", "zebra",
		"ördek", "kartal", "salyangoz", "maymun", "balina", "panter", "kaplan", "geyik", "kanarya",
		"kertenkele", "karınca", "köpek", "sinek", "pire", "şahin", "eşek", "domuz", "keçi",
		"akbaba", "koyun", "tilki", "ceylan", "çakal"];
	}
	else{
		array = ["penguin", "panda", "swallow", "chameleon", "giraffe", "parrot", "zebra",
		"duck", "eagle", "snails", "monkey", "whale", "panther", "tiger", "deer", "canary",
		"lizard", "ant", "dog", "fly", "flea", "hawk", "donkey", "pork", "goat",
		"vulture", "sheep", "fox", "gazelle", "coyote"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function goods(){
	if (language=="tr") {
		array = ["masa", "sandalye", "kanepe", "askı", "vazo" , "bavul", "süpürge", "pantolon",
		"bilgisayar", "halı", "lamba", "şemsiye", "sehpa", "koltuk", "minder", "avize", "tencere"
		, "ranza", "sürahi", "çaydanlık" , "bardak" , "peçete" , "havlu" , "bornoz" ,"perde"
		, "kaşık", "çatal", "bıçak", "kumanda", "fırın"];
	}
	else{
		array = ["table", "chair", "couch", "hanger", "vase", "suitcase", "broom", "pants"
		, "computer", "carpet", "lamp", "umbrella", "stand", "seat", "cushion", "chandelier", "pot",
		"bunk", "pitcher", "teapot", "cup", "napkin", "towel", "bathrobe", "curtain",
		"spoon", "fork", "knife", "command", "oven"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function country(){
	if (language=="tr") {
		array = ["Türkiye", "Amerika", "İngiltere", "İspanya", "Fransa", "Almanya", "İsveç", "Arjantin",
			"Brezilya", "Rusya", "Litvanya", "Yunanistan", "Şili", "Portekiz", "Danimarka", "Macaristan",
			"Belçika", "Avusturya", "Venezuela", "Irak", "Gana", "Gürcistan", "Paraguay",
			"Japonya", "Hollanda", "Azerbeycan", "Pakistan", "Suriye", "Romanya", "Moldova"];
	}
	else{
		array =["Turkey", "America", "England", "Spain", "France", "Germany", "Sweden", "Argentina",
			"Brasil", "Russia", "Lithuania", "Greece", "Chile", "Portugal", "Denmark", "Hungary",
			"Belgium", "Austria", "Venezuela", "Iraq", "Ghana", "Georgia", "Paraguay",
			"Japan", "Kenya", "Azerbaijan", "Pakistan", "Syria", "Romania", "Moldova"];
	}
	return array[Math.floor(Math.random() * 30)];
}

function plant(){
	if (language=="tr") {
		array = ["nane", "kekik", "papatya", "roka", "maydanoz", "marul", "lale", "kardelen",
			"dereotu", "fesleğen", "ıspanak", "pırasa", "lahana", "karnıbahar", "brokoli",
			"domates", "biber", "patlıcan", "avokado", "ananas", "armut", "portakal", "greyfurt",
			 "kestane", "kivi", "kiraz", "karpuz", "şalgam", "haşhaş", "kereviz"];
	}
	else{
		array = ["mint", "thyme", "daisy", "arugula", "parsley", "lettuce", "tulip", "snowdrop",
		"dill", "basil", "spinach", "leek", "cabbage", "cauliflower", "broccoli",
		"tomatoes", "pepper", "aubergine", "avocado", "pineapple", "pear", "orange", "grapefruit",
		"chestnut", "kiwi", "cherry", "watermelon", "turnip", "poppy", "celery"];
	}
	return array[Math.floor(Math.random() * 30)];
}
	<|endoftext|>


<commit_before>var Game = {};
var light = false;
var timerset = false;
var timersetflash = false;
Game.fps = 50;

Game.initialize = function() {
  this.entities = [];
  this.context = document.getElementById("viewport").getContext("2d");

};

function fadeOutRectangle(x, y, w, h, r, g, b) {

}

Game.draw = function() {

  this.context.clearRect(0, 0, 512, 288);

  this.context.fillStyle = "#1F3D5C";
  this.context.fillRect(0, 0, 512, 288);

  if(timersetflash == false){ //flash timer
    setTimeout(function(){
      light = false;
      timersetflash = false;
    }, 200);
    timersetflash = true;
  }

  if(light == true ){
    this.context.fillStyle = "#FFFFFF";
    this.context.fillRect(0, 0, 512, 288);

    var self = this;
    var r = 255;
    var g = 255;
    var b = 255;

    var steps = 50,
    var dr = (31 - r) / steps, // how much red should be added each time
    var dg = (61 - g) / steps, // green
    var db = (92 - b) / steps, // blue
    i = 0, // step counter
    interval = setInterval(function() {
      self.context.fillStyle = 'rgb(' + Math.round(r + dr * i) + ','
                               + Math.round(g + dg * i) + ','
                               + Math.round(b + db * i) + ')';
      self.context.fillRect(x, y, w, h); // will redraw the area each time
      i++;
      if(i === steps) { // stop if done
        clearInterval(interval);
      }
    }, 30);

    setTimeout(function() {
      light = false;
      timerset = false;
      flash = 0;
    }, 3000);
  }

  if(timerset == false){ //if we haven't set a timer yet, set one
    setTimeout(function(){
      light = true;
    }, 5000);
    timerset = true;
  }

  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].draw(this.context);
  }
};

Game.update = function() {
  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].update();
  }
};

Game.addRect = function(initX) {
  Game.entities.push(new Rect(initX));
};
Game.addRain = function() {
  Game.entities.push(new Rain());
};

Game.addPlayer = function(){
  Game.entites.push(new Player());
};
<commit_msg>Update game.js<commit_after>var Game = {};
var light = false;
var timerset = false;
var timersetflash = false;
Game.fps = 50;

Game.initialize = function() {
  this.entities = [];
  this.context = document.getElementById("viewport").getContext("2d");

};

Game.draw = function() {

  this.context.clearRect(0, 0, 512, 288);

  this.context.fillStyle = "#1F3D5C";
  this.context.fillRect(0, 0, 512, 288);

  if(timersetflash == false){ //flash timer
    setTimeout(function(){
      light = false;
      timersetflash = false;
    }, 200);
    timersetflash = true;
  }

  if(light == true ){
    this.context.fillStyle = "#FFFFFF";
    this.context.fillRect(0, 0, 512, 288);

    var self = this;
    var r = 255;
    var g = 255;
    var b = 255;

    var steps = 50,
    dr = (31 - r) / steps, // how much red should be added each time
    dg = (61 - g) / steps, // green
    db = (92 - b) / steps, // blue
    i = 0, // step counter
    interval = setInterval(function() {
      self.context.fillStyle = 'rgb(' + Math.round(r + dr * i) + ','
                               + Math.round(g + dg * i) + ','
                               + Math.round(b + db * i) + ')';
      self.context.fillRect(x, y, w, h); // will redraw the area each time
      i++;
      if(i === steps) { // stop if done
        clearInterval(interval);
      }
    }, 30);

    setTimeout(function() {
      light = false;
      timerset = false;
      flash = 0;
    }, 3000);
  }

  if(timerset == false){ //if we haven't set a timer yet, set one
    setTimeout(function(){
      light = true;
    }, 5000);
    timerset = true;
  }

  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].draw(this.context);
  }
};

Game.update = function() {
  for (var i=0; i < this.entities.length; i++) {
    this.entities[i].update();
  }
};

Game.addRect = function(initX) {
  Game.entities.push(new Rect(initX));
};
Game.addRain = function() {
  Game.entities.push(new Rain());
};

Game.addPlayer = function(){
  Game.entites.push(new Player());
};
<|endoftext|>


<commit_before>
var AlienFlock = function AlienFlock() {
  this.invulnrable = true;
  this.dx = 10; this.dy = 0;
  this.hit = 1; this.lastHit = 0;               //Controls the movment of the alien flock.
  this.speed = 10;

  this.draw = function() {};

  this.die = function() {
    if(Game.board.nextLevel()) {
      Game.loadBoard(new GameBoard(Game.board.nextLevel()));    //Detects when you have won the game.
    } else {
      Game.callbacks['win']();
    }
  }

  this.step = function(dt) {
    if(this.hit && this.hit != this.lastHit) {
      this.lastHit = this.hit;
      this.dy = this.speed;
    } else {
      this.dy=0;
    }
    this.dx = this.speed * this.hit;

    var max = {}, cnt = 0;
    this.board.iterate(function() {
      if(this instanceof Alien)  {
        if(!max[this.x] || this.y > max[this.x]) {
          max[this.x] = this.y;
        }
        cnt++;
      }
    });

    if(cnt == 0) { this.die(); }

    this.max_y = max;
    return true;
  };

}

var Alien = function Alien(opts) {
  this.flock = opts['flock'];
  this.frame = 0;
  this.mx = 0;
}

Alien.prototype.draw = function(canvas) {
  Sprites.draw(canvas,this.name,this.x,this.y,this.frame);
}

Alien.prototype.die = function() {
  GameAudio.play('die');
  this.flock.speed += 1;
  this.board.remove(this);
}

Alien.prototype.step = function(dt) {
  this.mx += dt * this.flock.dx;
  this.y += this.flock.dy;
  if(Math.abs(this.mx) > 10) {
    if(this.y == this.flock.max_y[this.x]) {
      this.fireSometimes();
    }
    this.x += this.mx;
    this.mx = 0;
    this.frame = (this.frame+1) % 2;
    if(this.x > Game.width - Sprites.map.alien1.w * 2) this.flock.hit = -1;
    if(this.x < Sprites.map.alien1.w) this.flock.hit = 1;
  }
  return true;
}

Alien.prototype.fireSometimes = function() {
      if(Math.random()*100 < 10) {
        this.board.addSprite('missile',this.x + this.w/2 - Sprites.map.missile.w/2,         //Controls the firing on alien weapons.
                                      this.y + this.h,
                                     { dy: 100 });
      }
}

var Player = function Player(opts) {
  this.reloading = 0;
}

Player.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'player',this.x,this.y);
}

Player.prototype.die = function() {
  GameAudio.play('die');
  Game.callbacks['die']();
}

Player.prototype.step = function(dt) {
  if(Game.keys['left']) { this.x -= 100 * dt; }
  if(Game.keys['right']) { this.x += 100 * dt; }

  if(this.x < 0) this.x = 0;
  if(this.x > Game.width-this.w) this.x = Game.width-this.w;

  this.reloading--;

  if(Game.keys['fire'] && this.reloading <= 0 && this.board.missiles < 3) {         //How many missiles you can fire in a row.
    GameAudio.play('fire');                                                         //Audio for firing missiles.
    this.board.addSprite('missile',                                                 //Adds the missile sprite.
                          this.x + this.w/2 - Sprites.map.missile.w/2,
                          this.y-this.h,
                          { dy: -100, player: true });
    this.board.missiles++;
    this.reloading = 10;                                                            //Amount of time it takes to reload?
  }
  return true;
}

var Missile = function Missile(opts) {
   this.dy = opts.dy;
   this.player = opts.player;
}

Missile.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'missile',this.x,this.y);
}

Missile.prototype.step = function(dt) {
   this.y += this.dy * dt;

   var enemy = this.board.collide(this);
   if(enemy) {
     enemy.die();
     return false;
   }
   return (this.y < 0 || this.y > Game.height) ? false : true;
}

Missile.prototype.die = function() {
  if(this.player) this.board.missiles--;
  if(this.board.missiles < 0) this.board.missiles=0;
   this.board.remove(this);
}
<commit_msg>added some comments to try and understand the level.js<commit_after>
var AlienFlock = function AlienFlock() {
  this.invulnrable = true;
  this.dx = 10; this.dy = 0;
  this.hit = 1; this.lastHit = 0;               //Controls the movment of the alien flock.
  this.speed = 10;

  this.draw = function() {};

  this.die = function() {
    if(Game.board.nextLevel()) {
      Game.loadBoard(new GameBoard(Game.board.nextLevel()));    //Detects when you've won the game.
    } else {
      Game.callbacks['win']();
    }
  }

  this.step = function(dt) {
    if(this.hit && this.hit != this.lastHit) {
      this.lastHit = this.hit;
      this.dy = this.speed;
    } else {
      this.dy=0;
    }
    this.dx = this.speed * this.hit;

    var max = {}, cnt = 0;
    this.board.iterate(function() {
      if(this instanceof Alien)  {
        if(!max[this.x] || this.y > max[this.x]) {
          max[this.x] = this.y;
        }
        cnt++;
      }
    });

    if(cnt == 0) { this.die(); }

    this.max_y = max;
    return true;
  };

}

var Alien = function Alien(opts) {
  this.flock = opts['flock'];
  this.frame = 0;
  this.mx = 0;
}

Alien.prototype.draw = function(canvas) {
  Sprites.draw(canvas,this.name,this.x,this.y,this.frame);
}

Alien.prototype.die = function() {
  GameAudio.play('die');
  this.flock.speed += 1;
  this.board.remove(this);
}

Alien.prototype.step = function(dt) {
  this.mx += dt * this.flock.dx;
  this.y += this.flock.dy;
  if(Math.abs(this.mx) > 10) {
    if(this.y == this.flock.max_y[this.x]) {
      this.fireSometimes();
    }
    this.x += this.mx;
    this.mx = 0;
    this.frame = (this.frame+1) % 2;
    if(this.x > Game.width - Sprites.map.alien1.w * 2) this.flock.hit = -1;
    if(this.x < Sprites.map.alien1.w) this.flock.hit = 1;
  }
  return true;
}

Alien.prototype.fireSometimes = function() {
      if(Math.random()*100 < 10) {
        this.board.addSprite('missile',this.x + this.w/2 - Sprites.map.missile.w/2,         //Controls the firing on alien weapons.
                                      this.y + this.h,
                                     { dy: 100 });
      }
}

var Player = function Player(opts) {
  this.reloading = 0;
}

Player.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'player',this.x,this.y);
}

Player.prototype.die = function() {
  GameAudio.play('die');
  Game.callbacks['die']();
}

Player.prototype.step = function(dt) {
  if(Game.keys['left']) { this.x -= 100 * dt; }
  if(Game.keys['right']) { this.x += 100 * dt; }

  if(this.x < 0) this.x = 0;
  if(this.x > Game.width-this.w) this.x = Game.width-this.w;

  this.reloading--;

  if(Game.keys['fire'] && this.reloading <= 0 && this.board.missiles < 3) {         //How many missiles you can fire in a row.
    GameAudio.play('fire');                                                         //Audio for firing missiles.
    this.board.addSprite('missile',                                                 //Adds the missile sprite.
                          this.x + this.w/2 - Sprites.map.missile.w/2,
                          this.y-this.h,
                          { dy: -100, player: true });
    this.board.missiles++;
    this.reloading = 10;                                                            //Amount of time it takes to reload?
  }
  return true;
}

var Missile = function Missile(opts) {
   this.dy = opts.dy;
   this.player = opts.player;
}

Missile.prototype.draw = function(canvas) {
   Sprites.draw(canvas,'missile',this.x,this.y);
}

Missile.prototype.step = function(dt) {
   this.y += this.dy * dt;

   var enemy = this.board.collide(this);
   if(enemy) {
     enemy.die();
     return false;
   }
   return (this.y < 0 || this.y > Game.height) ? false : true;
}

Missile.prototype.die = function() {
  if(this.player) this.board.missiles--;
  if(this.board.missiles < 0) this.board.missiles=0;
   this.board.remove(this);
}
<|endoftext|>


<commit_before>(function(root, factory) {
    "use strict";

    // Set up game appropriately for the environment. Start with AMD.
    //
    if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {

            root.SlotMachine = factory(root, exports, _, $);

        });

    } else if (typeof exports !== 'undefined') {
        var _ = require('underscore');
        factory(root, exports, _);

    } else {
        root.SlotMachine = factory(root, {}, root._, root.jQuery);
    }

    $.whenall = function(arr) {
        return $.when.apply($, arr).pipe(function() {
            return Array.prototype.slice.call(arguments);
        });
    };

}(this, function(root, SlotMachine, _, $) {
    "use strict";

    var transitionEnd = ["webkitTransitionEnd", "transitionend",
        "oTransitionEnd", "transitionend", "otransitionend"
    ].join(" ");

    /**
     * Reel or wheel is part of the slot machine;
     * Reel takes the container el and returns reel
     * operation methods like spin.
     */

    var Reel = SlotMachine.Reel = function(el) {
        this.$el = el;
    };

    Reel.prototype = {
        constructor: SlotMachine.Reel,
        spin: function(time, degree, index) {
            /**
             * Spins the reel with time and degree;
             * It returns the promise with index.
             */

            var dfd = new jQuery.Deferred();

            this.$el.css({
                "transform": "rotateX(-" + degree + "deg)",
                "transition": time + "ms"
            }).on(transitionEnd, function() {
                return dfd.resolve(index);
            });

            return dfd.promise();
        }
    }

    // Reels iterates over all options.reels and
    // creates instance of Reel class

    var Reels = SlotMachine.Reels = (function(options) {
        var reels = options.reels;

        var reel;
        var reelInstances = reels.map(function(reel) {
            reel = new Reel(reel.el);
            return reel.spin.bind(reel);
        });

        var callSpinReel = function(fn) {
            // spin time
            var time = _.random(1000, options.spinTime);

            // random number based on the reellength;
            var indx = _.random(0, options.reelLength - 1);

            var degree = indx * (360 / options.reelLength) + (360 * _.random(50, 100));

            return fn(time, degree, (indx > 2) ? Math.abs(indx - (options.reelLength / options.repeatItems)) : indx);
        }

        var startSpinning = function() {
            return reelInstances.map(callSpinReel);
        }

        return {
            startSpinning: startSpinning
        };

    });

    // Items collection has helper methods over the items in the wheel;
    // once the reel stops we got to match if item in each reel are of same kind;
    //

    var ItemCollection = SlotMachine.ItemCollection = (function(reels) {

        // with item indexs get items from each reel;

        var getSelectedItems = function(indxs) {
            return indxs.reduce(function(arr, indx, arrIndex) {
                return _(arr).push(reels[arrIndex].items[indx]);
            }, []);
        };

        var areItemsSameKind = function(indexs) {
            var selectedItems = getSelectedItems(indexs);

            // select the first element;
            var matchType = selectedItems[0].type;

            // check if there are other elements apart from the selected one;
            // if yes then no match; items are related with the 'TYPE' atttibute

            return !_.find(selectedItems, function(item) {
                return item.type !== matchType;
            }) ? matchType : false;
        };

        return {
            areItemsSameKind: areItemsSameKind
        };
    });

    var Game = SlotMachine.Game = function(options) {
        var defaultOptions = {
            spinTime: 10000
        };

        this.options = $.extend(defaultOptions, options);

        if (!this.options.reels) {
            throw new Error("Game items arugment missing");
        }

        this.reels = Reels(this.options);
        this.itemCollection = new ItemCollection(this.options.reels);
    };

    Game.prototype = {
        constructor: Game,
        play: function() {
            // returns promise; it spins the items, computes the result
            // and returns the result;
            var that = this;

            return $.whenall(this.reels.startSpinning()).then(function(result) {
                return that.itemCollection.areItemsSameKind(result);
            });
        },
        render: function() {
            var that = this;

            this.options.reels.map(function(reel) {
                // repeat items: if the number of items are less it hard
                // to form a wheel. Example with 3 items it will look like triangle

                reel.items = _.flatten(_.times(that.options.repeatItems, function() {
                    return reel.items;
                }));

                return reel;
            });

            var inject = function(reel) {
                reel.el.html(reel.items.map(that.options.template));
            };

            this.options.reels.map(inject);

            return new Game(this.options);
        }
    };

    return SlotMachine;
}));

$(function() {
    "use strict";

    var options = {
        spinTime: 1000, // spinning time in ms;
        template: _.template("
<%= name %>
"),
        repeatItems: 2,
        reelLength: 6,
        reels: [{
            el: $("#reel-1"),
            items: [{
                "name": "coffee maker",
                "type": "coffee"
            }, {
                "name": "teapot",
                "type": "tea"
            }, {
                "name": "espresso",
                "type": "espresso"
            }]
        }, {
            el: $("#reel-2"),
            items: [{
                "name": "coffee filter",
                "type": "coffee"
            }, {
                "name": "tea strainer",
                "type": "tea"
            }, {
                "name": "espresso tamper",
                "type": "espresso"
            }]
        }, {
            el: $("#reel-3"),
            items: [{
                "name": "coffee grounds",
                "type": "coffee"
            }, {
                "name": "loose tea",
                "type": "tea"
            }, {
                "name": "ground espresso beans",
                "type": "tea"
            }]
        }]
    };

    var game = new SlotMachine.Game(options).render();
    var $result = $("#result");

    $("#play").bind("click", function() {
        // reset the result;
        $result.html("");

        game.play().then(function(result) {
            if (!result) {
                return $result.html("Sorry, you did not win anything today. Better luck next time");
            }

            $result.html("Hurry! you won " + result + ". Enjoy!");

        }).fail(function(e) {
            console.log(e);
        });
    });
});<commit_msg>Fixing hints from jshint.<commit_after>(function(root, factory) {
    "use strict";

    // Set up game appropriately for the environment. Start with AMD.
    //
    if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {

            root.SlotMachine = factory(root, exports, _, $);

        });

    } else if (typeof exports !== 'undefined') {
        var _ = require('underscore');
        factory(root, exports, _);

    } else {
        root.SlotMachine = factory(root, {}, root._, root.jQuery);
    }

    $.whenall = function(arr) {
        return $.when.apply($, arr).pipe(function() {
            return Array.prototype.slice.call(arguments);
        });
    };

}(this, function(root, SlotMachine, _, $) {
    "use strict";

    var transitionEnd = ["webkitTransitionEnd", "transitionend",
        "oTransitionEnd", "transitionend", "otransitionend"
    ].join(" ");

    /**
     * Reel or wheel is part of the slot machine;
     * Reel takes the container el and returns reel
     * operation methods like spin.
     */

    var Reel = SlotMachine.Reel = function(el) {
        this.$el = el;
    };

    Reel.prototype = {
        constructor: SlotMachine.Reel,
        spin: function(time, degree, index) {
            /**
             * Spins the reel with time and degree;
             * It returns the promise with index.
             */

            var dfd = new jQuery.Deferred();

            this.$el.css({
                "transform": "rotateX(-" + degree + "deg)",
                "transition": time + "ms"
            }).on(transitionEnd, function() {
                return dfd.resolve(index);
            });

            return dfd.promise();
        }
    };

    // Reels iterates over all options.reels and
    // creates instance of Reel class

    var Reels = SlotMachine.Reels = (function(options) {
        var reels = options.reels;

        var reel;
        var reelInstances = reels.map(function(reel) {
            reel = new Reel(reel.el);
            return reel.spin.bind(reel);
        });

        var callSpinReel = function(fn) {
            // spin time
            var time = _.random(1000, options.spinTime);

            // random number based on the reellength;
            var indx = _.random(0, options.reelLength - 1);

            var degree = indx * (360 / options.reelLength) + (360 * _.random(50, 100));

            return fn(time, degree, (indx > 2) ? Math.abs(indx - (options.reelLength / options.repeatItems)) : indx);
        };

        var startSpinning = function() {
            return reelInstances.map(callSpinReel);
        };

        return {
            startSpinning: startSpinning
        };

    });

    // Items collection has helper methods over the items in the wheel;
    // once the reel stops we got to match if item in each reel are of same kind;
    //

    var ItemCollection = SlotMachine.ItemCollection = (function(reels) {

        // with item indexs get items from each reel;

        var getSelectedItems = function(indxs) {
            return indxs.reduce(function(arr, indx, arrIndex) {
                return _(arr).push(reels[arrIndex].items[indx]);
            }, []);
        };

        var areItemsSameKind = function(indexs) {
            var selectedItems = getSelectedItems(indexs);

            // select the first element;
            var matchType = selectedItems[0].type;

            // check if there are other elements apart from the selected one;
            // if yes then no match; items are related with the 'TYPE' atttibute

            return !_.find(selectedItems, function(item) {
                return item.type !== matchType;
            }) ? matchType : false;
        };

        return {
            areItemsSameKind: areItemsSameKind
        };
    });

    var Game = SlotMachine.Game = function(options) {
        var defaultOptions = {
            spinTime: 10000
        };

        this.options = $.extend(defaultOptions, options);

        if (!this.options.reels) {
            throw new Error("Game items arugment missing");
        }

        this.reels = Reels(this.options);
        this.itemCollection = new ItemCollection(this.options.reels);
    };

    Game.prototype = {
        constructor: Game,
        play: function() {
            // returns promise; it spins the items, computes the result
            // and returns the result;
            var that = this;

            return $.whenall(this.reels.startSpinning()).then(function(result) {
                return that.itemCollection.areItemsSameKind(result);
            });
        },
        render: function() {
            var that = this;

            this.options.reels.map(function(reel) {
                // repeat items: if the number of items are less it hard
                // to form a wheel. Example with 3 items it will look like triangle

                reel.items = _.flatten(_.times(that.options.repeatItems, function() {
                    return reel.items;
                }));

                return reel;
            });

            var inject = function(reel) {
                reel.el.html(reel.items.map(that.options.template));
            };

            this.options.reels.map(inject);

            return new Game(this.options);
        }
    };

    return SlotMachine;
}));

$(function() {
    "use strict";

    var options = {
        spinTime: 1000, // spinning time in ms;
        template: _.template("
<%= name %>
"),
        repeatItems: 2,
        reelLength: 6,
        reels: [{
            el: $("#reel-1"),
            items: [{
                "name": "coffee maker",
                "type": "coffee"
            }, {
                "name": "teapot",
                "type": "tea"
            }, {
                "name": "espresso",
                "type": "espresso"
            }]
        }, {
            el: $("#reel-2"),
            items: [{
                "name": "coffee filter",
                "type": "coffee"
            }, {
                "name": "tea strainer",
                "type": "tea"
            }, {
                "name": "espresso tamper",
                "type": "espresso"
            }]
        }, {
            el: $("#reel-3"),
            items: [{
                "name": "coffee grounds",
                "type": "coffee"
            }, {
                "name": "loose tea",
                "type": "tea"
            }, {
                "name": "ground espresso beans",
                "type": "tea"
            }]
        }]
    };

    var game = new SlotMachine.Game(options).render();
    var $result = $("#result");

    $("#play").bind("click", function() {
        // reset the result;
        $result.html("");

        game.play().then(function(result) {
            if (!result) {
                return $result.html("Sorry, you did not win anything today. Better luck next time");
            }

            $result.html("Hurry! you won " + result + ". Enjoy!");

        }).fail(function(e) {
            console.log(e);
        });
    });
});<|endoftext|>