<commit_before>var board,
    game = new Chess(),
    whiteDepth = 1,
    blackDepth = 1;

/*The "AI" part starts here */

/* board visualization and games state handling */

var onDragStart = function (source, piece, position, orientation) {
    if (game.in_checkmate() === true || game.in_draw() === true ||
        piece.search(/^b/) !== -1) {
        return false;
    }
};
var checkmate = function(game) {
    if(game.ugly_moves().length === 0)
    {
        var winner = movingnow + 'Checkmate';

        var checkmateCount = localStorage.getItem(winner)
        localStorage.setItem(winner, ++checkmateCount);
        log(winner);
        return winner;
    }else{
        var checkmateCount = localStorage.getItem('stalemate')
        localStorage.setItem('stalemate', ++checkmateCount);
        log('stalemate');
        return 'stalemate';
    }
};

var movingnow = '';

var whiteMove = function () {
    movingnow = 'white';
    //var bestMove = getBestMove(game, whiteDepth, minimaxRootWhite);
    //var bestMove = randomMove(game);
    //var bestMove = randomCapture(game);
    var bestMove = bestCapture(game);
    //var bestMove = avoidBeingCaptured(game);

    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());

    if (game.game_over()) {
        //alert('Game over ['+checkmate(game)+']');
        checkmate(game);
        stopGame();
        return;
    }
    window.setTimeout(blackMove, 5);
};

var blackMove = function () {
    movingnow = 'black';
    //var bestMove = getBestMove(game, blackDepth, minimaxRoot);
    //var bestMove = randomMove(game);
    var bestMove = randomCapture(game);
    //var bestMove = bestCapture(game);
    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());
    if (game.game_over()) {
      //  alert('Game over ['+checkmate(game)+']');
      checkmate(game);
      stopGame();
      return;
    }
    window.setTimeout(whiteMove, 5);
};

var getRandomMove = function(moves){
    //get random index
    var turnRandomIndex = Math.floor(Math.random() * moves.length);
    //get move from random index
    var randomMoove = moves[turnRandomIndex];
    //return move
    return randomMoove;
};

/**
 * RANDOMMOVE AI
 * @param {*} game
 */
var randomMove = function(game) {
    //get moves
    var turnPossibleMoves = game.ugly_moves();
    //get random move
    var randomMoove = getRandomMove(turnPossibleMoves);
    //return move
    return randomMoove;
};

/**
 * RANDOMCAPTURE AI
 * @param {*} possibleMoves
 */
var getCaptureMoves = function (possibleMoves) {
    //declare the capture moves array
    var captureMoves = [];
    //loop over all the moves
    var i = 0;
    while (i < possibleMoves.length) {
        //get a single move from all moves using the index
        var move = possibleMoves[i];
        //if the move is captured
        if (move.captured) {
            //add the move to the capture moves array
            captureMoves.push(move);
        }
        i++;
    }
    return captureMoves;
};

var randomCapture = function (game){
    //get all the capturemoves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare nextmove
    var nextMove;
    //if there are capturemoves, get  a random one
    if (captureMoves.length > 0) {
        nextMove = getRandomMove(captureMoves);
    } else {
        //else get any random move from the game
        nextMove = randomMove(game);
    }
    //return nextmove
    return nextMove;
};
/**
 * BESTCAPTURE AI
 * @param {*} game
 */
var bestCapture = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r' && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n' && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b' && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p' && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var resultsInCapture = function(theMove){
    game.ugly_move(theMove);
    var foundCapture = (getCaptureMoves(game.ugly_moves()).length > 0);
    game.undo();
    return foundCapture;
};

/**
 * AVOIDBEINGCAPTURED AI
 * @param {*} game
 */
var avoidBeingCaptured = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
        if(resultsInCapture(theMove))
        {
            theMove = randomMove(game);
        }
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r'
                && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n'
                && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b'
                && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p'
                && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var positionCount;
var getBestMove = function (game, depth, findBestMove) {
    if (game.game_over()) {
        //alert('Game over');
        return;
    }

    positionCount = 0;
    //var depth = parseInt($('#search-depth').find(':selected').text());

    var d = new Date().getTime();
    var bestMove = findBestMove(depth, game, true);
    var d2 = new Date().getTime();
    var moveTime = (d2 - d);
    var positionsPerS = ( positionCount * 1000 / moveTime);

    $('#position-count').text(positionCount);
    $('#time').text(moveTime/1000 + 's');
    $('#positions-per-s').text(positionsPerS);
    return bestMove;
};

var renderMoveHistory = function (moves) {
    var historyElement = $('#move-history').empty();
    historyElement.empty();
    for (var i = 0; i < moves.length; i = i + 2) {
        historyElement.append('' + moves[i] + ' ' + ( moves[i + 1] ? moves[i + 1] : ' ') + '
')
    }
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var log = function (text) {
    var historyElement = $('#move-history');
    historyElement.append('' + text + '
');
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var onDrop = function (source, target) {

    // Removing to make both sides fully CPU, not first move as human
    // var move = game.move({
    //     from: source,
    //     to: target,
    //     promotion: 'q'
    // });
    startGame();
};
var startGame = function() {
    removeGreySquares();
    // if (move === null) {
    //     return 'snapback';
    // }

    renderMoveHistory(game.history());
    window.setTimeout(whiteMove, 1000);
};
var stopGame = function () {
    var whiteCheckmate = parseInt(localStorage.getItem('whiteCheckmate'));
    whiteCheckmate = whiteCheckmate ? whiteCheckmate : 0;
    var blackCheckmate = parseInt(localStorage.getItem('blackCheckmate'));
    blackCheckmate = blackCheckmate ? blackCheckmate : 0;
    var stalemate = parseInt(localStorage.getItem('stalemate'));
    stalemate = stalemate ? stalemate : 0;
    if (whiteCheckmate + blackCheckmate + stalemate >= 100) {
        var result = " black checkmate: "+blackCheckmate + ", " + " white checkmate: "+ whiteCheckmate + "," + " stalemate: "+stalemate;
        //log the results
        log(result);
        //alert the results
        alert(result);
        localStorage.removeItem('whiteCheckmate');
        localStorage.removeItem('blackCheckmate');
        localStorage.removeItem('stalemate');
    }else{
        //automatically reload here
        location.reload();
    }
};

var onSnapEnd = function () {
    board.position(game.fen());
};

var onMouseoverSquare = function(square, piece) {
    var moves = game.moves({
        square: square,
        verbose: true
    });

    if (moves.length === 0) return;

    greySquare(square);

    for (var i = 0; i < moves.length; i++) {
        greySquare(moves[i].to);
    }
};

var onMouseoutSquare = function(square, piece) {
    removeGreySquares();
};

var removeGreySquares = function() {
    $('#board .square-55d63').css('background', '');
};

var greySquare = function(square) {
    var squareEl = $('#board .square-' + square);

    var background = '#a9a9a9';
    if (squareEl.hasClass('black-3c85d') === true) {
        background = '#696969';
    }

    squareEl.css('background', background);
};

var cfg = {
    draggable: true,
    position: 'start',
    onDragStart: onDragStart,
    onDrop: onDrop,
    onMouseoutSquare: onMouseoutSquare,
    onMouseoverSquare: onMouseoverSquare,
    onSnapEnd: onSnapEnd
};
board = ChessBoard('board', cfg);

startGame();<commit_msg>Routine Check-In<commit_after>var board,
    game = new Chess(),
    whiteDepth = 1,
    blackDepth = 1;

/*The "AI" part starts here */

/* board visualization and games state handling */

var onDragStart = function (source, piece, position, orientation) {
    if (game.in_checkmate() === true || game.in_draw() === true ||
        piece.search(/^b/) !== -1) {
        return false;
    }
};
var checkmate = function(game) {
    if(game.ugly_moves().length === 0)
    {
        var winner = movingnow + 'Checkmate';

        var checkmateCount = localStorage.getItem(winner)
        localStorage.setItem(winner, ++checkmateCount);
        log(winner);
        return winner;
    }else{
        var checkmateCount = localStorage.getItem('stalemate')
        localStorage.setItem('stalemate', ++checkmateCount);
        log('stalemate');
        return 'stalemate';
    }
};

var movingnow = '';

var whiteMove = function () {
    movingnow = 'white';
    //var bestMove = getBestMove(game, whiteDepth, minimaxRootWhite);
    //var bestMove = randomMove(game);
    //var bestMove = randomCapture(game);
    var bestMove = bestCapture(game);
    //var bestMove = avoidBeingCaptured(game);

    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());

    if (game.game_over()) {
        //alert('Game over ['+checkmate(game)+']');
        checkmate(game);
        stopGame();
        return;
    }
    window.setTimeout(blackMove, 5);
};

var blackMove = function () {
    movingnow = 'black';
    //var bestMove = getBestMove(game, blackDepth, minimaxRoot);
    var bestMove = randomMove(game);
    //var bestMove = randomCapture(game);
    //var bestMove = bestCapture(game);
    game.ugly_move(bestMove);
    board.position(game);
    renderMoveHistory(game.history());
    if (game.game_over()) {
      //  alert('Game over ['+checkmate(game)+']');
      checkmate(game);
      stopGame();
      return;
    }
    window.setTimeout(whiteMove, 5);
};

var getRandomMove = function(moves){
    //get random index
    var turnRandomIndex = Math.floor(Math.random() * moves.length);
    //get move from random index
    var randomMoove = moves[turnRandomIndex];
    //return move
    return randomMoove;
};

/**
 * RANDOMMOVE AI
 * @param {*} game
 */
var randomMove = function(game) {
    //get moves
    var turnPossibleMoves = game.ugly_moves();
    //get random move
    var randomMoove = getRandomMove(turnPossibleMoves);
    //return move
    return randomMoove;
};

/**
 * RANDOMCAPTURE AI
 * @param {*} possibleMoves
 */
var getCaptureMoves = function (possibleMoves) {
    //declare the capture moves array
    var captureMoves = [];
    //loop over all the moves
    var i = 0;
    while (i < possibleMoves.length) {
        //get a single move from all moves using the index
        var move = possibleMoves[i];
        //if the move is captured
        if (move.captured) {
            //add the move to the capture moves array
            captureMoves.push(move);
        }
        i++;
    }
    return captureMoves;
};

var randomCapture = function (game){
    //get all the capturemoves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare nextmove
    var nextMove;
    //if there are capturemoves, get  a random one
    if (captureMoves.length > 0) {
        nextMove = getRandomMove(captureMoves);
    } else {
        //else get any random move from the game
        nextMove = randomMove(game);
    }
    //return nextmove
    return nextMove;
};
/**
 * BESTCAPTURE AI
 * @param {*} game
 */
var bestCapture = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r' && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n' && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b' && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p' && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var resultsInCapture = function(theMove){
    game.ugly_move(theMove);
    var foundCapture = (getCaptureMoves(game.ugly_moves()).length > 0);
    game.undo();
    return foundCapture;
};

/**
 * AVOIDBEINGCAPTURED AI
 * @param {*} game
 */
var avoidBeingCaptured = function (game) {
    //get all the capture moves
    var captureMoves = getCaptureMoves(game.ugly_moves());
    //declare move var
    var theMove;

    //If there are no capture moves, then make a random move
    if (captureMoves.length === 0) {
        theMove = randomMove(game);
        if(resultsInCapture(theMove))
        {
            theMove = randomMove(game);
        }
    } else {
        //if there are capture moves, select the most valuable piece

        //first, get the first capture move
        theMove = captureMoves[0];

        //loop over all the capture moves comparing the one we have to the next one
        for (i = 0; i < captureMoves.length; i++) {
            //compare the captured piece to the next move's captured piece.
            var theOtherMove = captureMoves[i];
            //choose the move with the best captured piece
            //if the captured piece is a king, do it
            if (theMove.captured === 'k') {
                break;
            }
            //if there are no captures that result in a king, search for a queen
            else if(theMove.captured === 'q' && 'k'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no queen captures, find a rook
            else if(theMove.captured === 'r'
                && 'kq'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no rooks to capture, find a knight
            else if(theMove.captured === 'n'
                && 'kqr'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if there are no knights, find a pawn
            else if(theMove.captured === 'b'
                && 'kqrn'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
            //if you've gotten this far, there has to be a pawn.
            else if(theMove.captured === 'p'
                && 'kqrnb'.search(theOtherMove.captured) > -1){
                theMove = theOtherMove;
            }
        }
    }
    return theMove;
};

var positionCount;
var getBestMove = function (game, depth, findBestMove) {
    if (game.game_over()) {
        //alert('Game over');
        return;
    }

    positionCount = 0;
    //var depth = parseInt($('#search-depth').find(':selected').text());

    var d = new Date().getTime();
    var bestMove = findBestMove(depth, game, true);
    var d2 = new Date().getTime();
    var moveTime = (d2 - d);
    var positionsPerS = ( positionCount * 1000 / moveTime);

    $('#position-count').text(positionCount);
    $('#time').text(moveTime/1000 + 's');
    $('#positions-per-s').text(positionsPerS);
    return bestMove;
};

var renderMoveHistory = function (moves) {
    var historyElement = $('#move-history').empty();
    historyElement.empty();
    for (var i = 0; i < moves.length; i = i + 2) {
        historyElement.append('' + moves[i] + ' ' + ( moves[i + 1] ? moves[i + 1] : ' ') + '
')
    }
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var log = function (text) {
    var historyElement = $('#move-history');
    historyElement.append('' + text + '
');
    historyElement.scrollTop(historyElement[0].scrollHeight);

};
var onDrop = function (source, target) {

    // Removing to make both sides fully CPU, not first move as human
    // var move = game.move({
    //     from: source,
    //     to: target,
    //     promotion: 'q'
    // });
    startGame();
};
var startGame = function() {
    removeGreySquares();
    // if (move === null) {
    //     return 'snapback';
    // }

    renderMoveHistory(game.history());
    window.setTimeout(whiteMove, 1000);
};
var stopGame = function () {
    var whiteCheckmate = parseInt(localStorage.getItem('whiteCheckmate'));
    whiteCheckmate = whiteCheckmate ? whiteCheckmate : 0;
    var blackCheckmate = parseInt(localStorage.getItem('blackCheckmate'));
    blackCheckmate = blackCheckmate ? blackCheckmate : 0;
    var stalemate = parseInt(localStorage.getItem('stalemate'));
    stalemate = stalemate ? stalemate : 0;
    if (whiteCheckmate + blackCheckmate + stalemate >= 100) {
        var result = " black checkmate: "+blackCheckmate + ", " + " white checkmate: "+ whiteCheckmate + "," + " stalemate: "+stalemate;
        //log the results
        log(result);
        //alert the results
        alert(result);
        localStorage.removeItem('whiteCheckmate');
        localStorage.removeItem('blackCheckmate');
        localStorage.removeItem('stalemate');
    }else{
        //automatically reload here
        location.reload();
    }
};

var onSnapEnd = function () {
    board.position(game.fen());
};

var onMouseoverSquare = function(square, piece) {
    var moves = game.moves({
        square: square,
        verbose: true
    });

    if (moves.length === 0) return;

    greySquare(square);

    for (var i = 0; i < moves.length; i++) {
        greySquare(moves[i].to);
    }
};

var onMouseoutSquare = function(square, piece) {
    removeGreySquares();
};

var removeGreySquares = function() {
    $('#board .square-55d63').css('background', '');
};

var greySquare = function(square) {
    var squareEl = $('#board .square-' + square);

    var background = '#a9a9a9';
    if (squareEl.hasClass('black-3c85d') === true) {
        background = '#696969';
    }

    squareEl.css('background', background);
};

var cfg = {
    draggable: true,
    position: 'start',
    onDragStart: onDragStart,
    onDrop: onDrop,
    onMouseoutSquare: onMouseoutSquare,
    onMouseoverSquare: onMouseoverSquare,
    onSnapEnd: onSnapEnd
};
board = ChessBoard('board', cfg);

startGame();<|endoftext|>


<commit_before>$(function() {
    if (localStorage.notepad != undefined) {
        var i = 0;
        var j = 0;
        var notas = JSON.parse(localStorage.getItem('notepad'));
        while (notas.length > i) {
            $('tr:last > td[info="nome"]').html(notas[i][j++]);
            $('tr:last > td[info="nota1"]').html(notas[i][j++]);
            $('tr:last > td[info="nota2"]').html(notas[i][j++]);
            $('tr:last > td[info="nota3"]').html(notas[i][j++]);
            $('tr:last > td[info="nota4"]').html(notas[i++][j++]);
            addLinha()
        }
        preencheTab();
    };

    $(document).keypress(function(e) {
        if (e.which == 13 && e.target.nodeName == 'INPUT') {
            e.target.blur();
        }
    });

    $('body').on('dblclick', 'td', function() {
        if ($(this).attr('info') == 'nome' && $(this).children().prop('tagName') != 'INPUT') {
            if ($(this).html() != '---')
                $(this).html('<input type="text" class="form-control" value="' + $(this).html() + '">');
            else
                $(this).html('<input type="text" class="form-control">');
            $(this).children().focus();
        };
    });

    $('body').on('dblclick', 'td', function() {
        if ($(this).attr('info') != 'nome' && $(this).attr('info') != 'exame' && $(this).attr('info') != 'falta' && $(this).children().prop('tagName') != 'INPUT') {
            if ($(this).html() != '---')
                $(this).html('<input type="number" class="form-control" value="' + $(this).html() + '">');
            else
                $(this).html('<input type="number" class="form-control">');
            $(this).children().focus();
        };
    });

    $('body').on('blur', 'td', function() {
        if ($(this).attr('info') != 'nome' && ($(this).children().val() == '' || $(this).children().val() == '---')) {
            $(this).html('---');
            preencheTab();
            return
        }

        if ($(this).children().val() == '' || $(this).children().val() == '---') {
            if ($('tr:last').attr('linha') != 1 && ($('tr:last').children().first().html() == '---' || $('tr:last').children().first().html() == '---')) {
                if (parseInt(($(this).parent().attr('linha'))) > 0) {
                    $(this).parent().remove();
                    var linha = 1;
                    $('table tr').each(function() {
                        if (parseInt($(this).attr('linha')) > 0)
                            $(this).attr('linha', linha++);
                    });
                    preencheTab();
                    return
                }
            }
            $(this).html('---');

        } else {
            $(this).html($(this).children().val());
            if ($('tr:last > td[info="nome"]').html() != '---')
                addLinha();
        }
        preencheTab()
    });
});

function addLinha() {
    var linha = $('table tr').length - 1;
    $('table').html($('table').html() +
        `<tr linha="` + linha + `">
    ---
    ---
    ---
    ---
    ---
    ---
    ---

`);
};

function preencheTab() {
    $('tr[linha]').each(function() {
        if ($(this).children().first().html() != '---') {
            $('tr[linha="' + linha + '"] > td[info="falta"]').html('---');
            $('tr[linha="' + linha + '"] > td[info="exame"]').html('---');
            var linha = $(this).attr('linha');
            var soma = 0;
            if (isNaN(parseInt($(this).children().first().next().html())) != true)
                soma += parseFloat($(this).children().first().next().html());
            if (isNaN(parseInt($(this).children().first().next().next().html())) != true)
                soma += parseFloat($(this).children().first().next().next().html());
            if (isNaN(parseInt($(this).children().first().next().next().next().html())) != true)
                soma += parseFloat($(this).children().first().next().next().next().html());
            if (isNaN(parseInt($(this).children().first().next().next().next().next().html())) != true)
                soma += parseFloat($(this).children().first().next().next().next().next().html());
            $('tr[linha="' + linha + '"] > td[info="falta"]').html(28 - soma > 0 ? Math.round((28 - soma) * 10) / 10 : 0);
            $('tr[linha="' + linha + '"] > td[info="exame"]').html(28 - soma > 0 ? Math.ceil(((5 - (soma / 4 * 0.6)) / 0.4) * 10) / 10 : '---');
        }
    });
    var global = []
    $('tr[linha]').each(function() {
        localStorage.clear();
        var i = 0;
        var nota = $(this).children();
        var fix = [];
        while (5 > i) {
            if (nota[i].innerHTML == '---' && nota[i].getAttribute('info') == 'nome')
                break;
            fix[fix.length] = nota[i].innerHTML;
            i++
        }
        if (fix.length > 2)
            global[global.length] = fix
    });
    localStorage.setItem('notepad', JSON.stringify(global));
};
<commit_msg>BUG SOLVED<commit_after>$(function() {
    if (localStorage.notepad != undefined) {
        var i = 1;
        var j = 0;
        var linha = 2;
        var notas = JSON.parse(localStorage.getItem('notepad'));
        var next;

        $('tr:last > td[info="nome"]').html(notas[0][0]);
        $('tr:last > td[info="nota1"]').html(notas[0][1]);
        $('tr:last > td[info="nota2"]').html(notas[0][2]);
        $('tr:last > td[info="nota3"]').html(notas[0][3]);
        $('tr:last > td[info="nota4"]').html(notas[0][4]);
        while (notas.length > i) {
            next = $('

');
            next.append(''+notas[i][j++]+'	');
            next.append(''+notas[i][j++]+'	');
            next.append(''+notas[i][j++]+'	');
            next.append(''+notas[i][j++]+'	');
            next.append(''+notas[i++][j++]+'	');
            next.append('---	');
            next.append('---	');
            $('table').append(next);
            linha++;
        };
        addLinha();
        preencheTab();
    };

    $(document).keypress(function(e) {
        if (e.which == 13 && e.target.nodeName == 'INPUT') {
            e.target.blur();
        }
    });

    $('body').on('dblclick', 'td', function() {
        if ($(this).attr('info') == 'nome' && $(this).children().prop('tagName') != 'INPUT') {
            if ($(this).html() != '---')
                $(this).html('<input type="text" class="form-control" value="' + $(this).html() + '">');
            else
                $(this).html('<input type="text" class="form-control">');
            $(this).children().focus();
        };
    });

    $('body').on('dblclick', 'td', function() {
        if ($(this).attr('info') != 'nome' && $(this).attr('info') != 'exame' && $(this).attr('info') != 'falta' && $(this).children().prop('tagName') != 'INPUT') {
            if ($(this).html() != '---')
                $(this).html('<input type="number" class="form-control" value="' + $(this).html() + '">');
            else
                $(this).html('<input type="number" class="form-control">');
            $(this).children().focus();
        };
    });

    $('body').on('blur', 'td', function() {
        if ($(this).attr('info') != 'nome' && ($(this).children().val() == '' || $(this).children().val() == '---')) {
            $(this).html('---');
            preencheTab();
            return
        }

        if ($(this).children().val() == '' || $(this).children().val() == '---') {
            if ($('tr:last').attr('linha') != 1 && ($('tr:last').children().first().html() == '---' || $('tr:last').children().first().html() == '---')) {
                if (parseInt(($(this).parent().attr('linha'))) > 0) {
                    $(this).parent().remove();
                    var linha = 1;
                    $('table tr').each(function() {
                        if (parseInt($(this).attr('linha')) > 0)
                            $(this).attr('linha', linha++);
                    });
                    preencheTab();
                    return
                }
            }
            $(this).html('---');

        } else {
            $(this).html($(this).children().val());
            if ($('tr:last > td[info="nome"]').html() != '---')
                addLinha();
        }
        preencheTab()
    });
});

function addLinha() {
    var linha = $('table tr').length - 1;
    $('table').html($('table').html() +
        `<tr linha="` + linha + `">
    ---
    ---
    ---
    ---
    ---
    ---
    ---

`);
};

function preencheTab() {
    $('tr[linha]').each(function() {
        if ($(this).children().first().html() != '---') {
            $('tr[linha="' + linha + '"] > td[info="falta"]').html('---');
            $('tr[linha="' + linha + '"] > td[info="exame"]').html('---');
            var linha = $(this).attr('linha');
            var soma = 0;
            if (isNaN(parseInt($(this).children().first().next().html())) != true)
                soma += parseFloat($(this).children().first().next().html());
            if (isNaN(parseInt($(this).children().first().next().next().html())) != true)
                soma += parseFloat($(this).children().first().next().next().html());
            if (isNaN(parseInt($(this).children().first().next().next().next().html())) != true)
                soma += parseFloat($(this).children().first().next().next().next().html());
            if (isNaN(parseInt($(this).children().first().next().next().next().next().html())) != true)
                soma += parseFloat($(this).children().first().next().next().next().next().html());
            $('tr[linha="' + linha + '"] > td[info="falta"]').html(28 - soma > 0 ? Math.round((28 - soma) * 10) / 10 : 0);
            $('tr[linha="' + linha + '"] > td[info="exame"]').html(28 - soma > 0 ? Math.ceil(((5 - (soma / 4 * 0.6)) / 0.4) * 10) / 10 : '---');
        }
    });
    var global = []
    $('tr[linha]').each(function() {
        localStorage.clear();
        var i = 0;
        var nota = $(this).children();
        var fix = [];
        while (5 > i) {
            if (nota[i].innerHTML == '---' && nota[i].getAttribute('info') == 'nome')
                break;
            fix[fix.length] = nota[i].innerHTML;
            i++
        }
        if (fix.length > 2)
            global[global.length] = fix
    });
    localStorage.setItem('notepad', JSON.stringify(global));
};
<|endoftext|>


<commit_before>function init() {
    var r1 = init_screens();

    if (r1) {
        init_loadingImages();
        init_info();
    } else {
        // console.log('poop');
        //can't play, stoppppp
        uponFailure();
    }
}

init();

function init_screens() {
    //screen sizes
    var wx = window.innerWidth,
        wy = window.innerHeight;
    library.scr[0] = wx;
    library.scr[1] = wy;
    library.canvas[0] = wx;
    library.canvas[1] = wy;
    var m;
    if (wx < 400) {
        m = 0.75;
    } else if (wx >= 400 && wx < 1000) {
        m = 1.25;
    } else if (wx >= 1000 && wx < 1600) {
        m = 1.5;
    } else if (wx >= 1600) {
        m = 2;
    } else {
        m = 1;
    }
    library.multiplier = m;

    //set the message position
    elements.message.style.top = library.scr[1] * 0.45 + 'px';

    //test out canvas capability
    elements.c = elements.canvas.getContext('2d');
    var result;
    if (elements.c !== null) {
        elements.canvas.setAttribute('height', library.canvas[1]);
        elements.canvas.setAttribute('width', library.canvas[0]);
        result = true;
    } else {
        //we can't play this game, tell the person to update browser
        library.data.poop = true;
        result = false;
    }
    return result;
}

function init_loadingImages() {
    var assets = [library.pim, library.magic, library.portal, library.poof, library.skull, library.bg, library.excla];
    var music = [library.ghost_sound, library.zombie_sound, library.transform_sound, library.portal_sound, library.player_sound];
    library.pim.src = 'images/pimsheet.svg';
    library.magic.src = 'images/magic.svg';
    library.portal.src = 'images/portal.svg';
    library.poof.src = 'images/poof.svg';
    library.skull.src = 'images/skull.svg';
    library.bg.src = 'images/background.jpg';
    library.excla.src = 'images/exclamation.svg';

    library.ghost_sound.src = 'track/Ghost_01.wav';
    library.zombie_sound.src = 'track/Action-02.wav';
    library.transform_sound.src = 'track/Powerup_01.wav';
    library.portal_sound.src = 'track/Portal-01.wav';
    library.player_sound.src = 'track/Function-Change-01.wav';

    for (var i = 0; i < assets.length; i++) {
        assets[i].addEventListener('load', finishedLoading, false);
    }
    for (var j = 0; j < music.length; j++) {
        music[j].addEventListener('canplay', finishedLoading, false);
    }
}

function init_info() {
    //check localStorage
    checkLocalStorage();

    //set the player action
    var playerRandom = Math.floor(Math.random() * 3);
    game.player = library.data.player[playerRandom];
    // console.log('the initial action is: ' + game.player);
    elements.player_action.textContent = game.player;

    //add functionality to opening screen
    prepareScreen();

    //add sound control to the info context
    elements.music.addEventListener('click', toggleSound, false);
}

function prepareScreen() {
    //event listeners
    elements.play.addEventListener('click', goToGame, false);
    elements.open_tutorial.addEventListener('click', accessTutorial, false);
}
function goToGame() {
    //hide opening, show game
    elements.opening.style.opacity = 0;
    elements.opening.addEventListener('transitionend', goToGameScreen, false);
}
function goToGameScreen() {
    elements.opening.removeEventListener('transitionend', goToGameScreen, false);
    elements.opening.classList.add('hidden');
    elements.game.classList.remove('hidden');
    window.setTimeout(function() {
        elements.game.style.opacity = 1;
        elements.game.addEventListener('transitionend', prepGame, false);
    }, 100);
}
function prepGame() {
    console.log('the game should be starting');
    elements.game.removeEventListener('transitionend', prepGame, false);
    message('get ready', 2500);
    //start game
    window.setTimeout( function() {
        message('go!', 750);
        game_start();
    }, 3000);
}

function game_start() {
    //clean everything up
    elements.c.clearRect(0, 0, library.canvas[0], library.canvas[1]);
    elements.c.globalAlpha = 1;
    reset_game_info('game');

    //start the time
    game.start = new Date();
    game.running = true;
    initCreate();

    //start the intervals
    game.player_loop = window.setInterval(player_change_action, 5000);
    game.loop = window.setInterval(gameUpdate, 100);

    //add event listeners
    elements.help_button.addEventListener('click', showHelp, false);
    elements.canvas.addEventListener('click', pushPim, false);
}
function reset_game_info(forwhat) {
    game.start = 0;
    game.end = 0;
    game.total = 0;
    game.score = 0;

    game.running = false;
    game.finished = false;

    if (forwhat === 'tutorial') {
        game.pims.length = 0;
        game.skulls.length = 0;
        game.magic.length = 0;

        game.limit[0] = 1;
        game.limit[1] = 0;
        game.limit[2] = 0;
    } else {
        //it's for the game
        game.round = library.data.rounds;
        game.pims.length = 0;
        game.skulls.length = 0;
        game.magic.length = 0;

        game.limit[0] = game.round + 3;
        game.limit[1] = game.round + 3;
        game.limit[2] = Math.floor(Math.random() * 5) + game.round * 2 + 10;
    }

    window.clearInterval(game.loop);
    window.clearInterval(game.player_loop);
    game.player = library.data.player[Math.floor(Math.random() * 3)];
}
function roundOver() {
    //congratulations!

    //stop things that need to be stopped
    game.running = false;
    game.finished = true;
    window.clearInterval(game.player_loop);
    elements.canvas.removeEventListener('click', pushPim, false);

    //what's our ending info?
    game.end = new Date();
    //take into account the saved time from pauses later
    var total = (game.end.getTime() - game.start.getTime()) / 1000 / 60;
    game.total += total;

    library.data.rounds++;
    var score = ( library.data.rounds * ((game.limit[0] / 3) + 3) * 1000 ) - (total * 60 * 2);
    score = Math.round(score);
    game.score = score;
    checkHighscore(score);

    showEnd();
}

//other stuff
function checkHighscore(num) {
    if (num && num > library.data.highscore) {
        library.data.highscore = num;
        window.localStorage['pimbo'] = num;
    }
}
function checkLocalStorage() {
    //does the localStorage exist?
    if (window.localStorage['pimbo']) {
        var hs = Number(window.localStorage['pimbo']);
        library.data.highscore = hs;
        elements.highscore_open.textContent = hs;
        elements.highscore_open.parentElement.classList.remove('hidden');
    } else {
        window.localStorage.setItem('pimbo', 0);
    }
}

function showHelp() {
    //pause game
    game.running = false;
    window.clearInterval(game.loop);
    window.clearInterval(game.player_loop);

    //note the time
    game.end = new Date();

    var total = (game.end.getTime() - game.start.getTime()) / 1000 / 60;
    game.total += total;

    //update help info
    updateHelpInfo();

    //show the help
    elements.info.classList.remove('hidden');
    window.setTimeout( function() {
        elements.info.style.opacity = 1;
    }, 100);
    elements.help_button.classList.remove('helphover');

    //event listeners
    elements.canvas.removeEventListener('click', pushPim, false);
    elements.help_button.removeEventListener('click', showHelp, false);
    elements.info_close.addEventListener('click', hideHelp, false);
}
function updateHelpInfo() {
    var hs;
    var prettyTime = Math.floor(game.total) + ':';
    prettyTime += 60 * (1 - (Math.ceil(game.total) - game.total));

    elements.info_round.textContent = library.data.rounds + 1;
    elements.info_time.textContent = Math.round(game.total * 60)+ ' seconds';

    if (library.data.highscore) {
        hs = library.data.highscore;
    } else {
        hs = 'noop';
    }
    elements.highscore_info.textContent = hs;
}
function hideHelp() {
    //hide the help
    elements.info.style.opacity = 0;

    //evnt listeners and stuff
    elements.help_button.classList.add('helphover');
    elements.info_close.removeEventListener('click', hideHelp, false);
    elements.info.addEventListener('transitionend', startGameAgain, false);

}
function startGameAgain() {
    elements.info.removeEventListener('transitionend', startGameAgain, false);
    elements.info.classList.add('hidden');

    window.setTimeout( function() {
        //start the game again
        game.running = true;
        game.start = new Date();
        game.player_loop = window.setInterval(player_change_action, 5000);
        game.loop = window.setInterval(gameUpdate, 100);

        //add event listeners
        elements.help_button.addEventListener('click', showHelp, false);
        elements.canvas.addEventListener('click', pushPim, false);

    }, 200);
}

function showEnd() {
    //update ending info

    elements.end_message.textContent = endGameMessage();
    elements.end_ghosts.textContent = game.limit[0] + ' pims';
    elements.end_time.textContent = Math.round(game.total * 60) + ' seconds';
    elements.end_score.textContent = game.score;
    elements.highscore_end.textContent = library.data.highscore;
    elements.highscore_end.parentElement.classList.remove('hidden');

    //show the end
    elements.help_button.classList.remove('helphover');
    elements.ending.classList.remove('hidden');
    window.setTimeout(function() {
        elements.ending.style.opacity = 1;
    }, 500);

    //event listeners
    elements.canvas.removeEventListener('click', pushPim, false);
    elements.help_button.removeEventListener('click', showHelp, false);
    elements.play_again.addEventListener('click', playAgain, false);
}
function playAgain() {
    //hide the ending
    elements.ending.style.opacity = 0;
    elements.ending.addEventListener('transitionend', showGameScreenAgain, false);
}
function showGameScreenAgain() {
    this.removeEventListener('transitionend', showGameScreenAgain, false);
    elements.ending.classList.add('hidden');

    //event listeners
    elements.play_again.removeEventListener('click', playAgain, false);
    elements.canvas.addEventListener('click', pushPim, false);
    elements.help_button.addEventListener('click', showHelp, false);
    elements.help_button.classList.add('helphover');

    message('get ready', 2000);
    window.setTimeout(function() {
        game_start();
        message('go!', 500);
    }, 2000);

}

function message(str, t) {
    //add a message to the screen
    elements.message.textContent = str;

    //show the message
    elements.message.classList.remove('hidden');

    //hide if after how many seconds?
    window.setTimeout( function() {
        elements.message.classList.add('hidden');
    }, t);
}

function toggleSound() {
    if (library.data.music) {
        library.data.music = false;
        elements.music.textContent = 'sound is off';
    } else {
        library.data.music = true;
        elements.music.textContent = 'sound is on';
    }
}

function uponFailure() {
    var fail = document.createElement('p');
    fail.innerHTML = 'Sorry, this browser does not support canvas. You need canvas to play this game. Please consider another browser for your gaming pleasure.';
    elements.loading.appendChild(fail);
}

function finishedLoading() {
    // console.log(this + ' finished loading');
    this.volume *= 0.45;
    this.removeEventListener('load', finishedLoading, false);
    library.assetsLoaded++;

    if (library.assetsLoaded === library.totalAssets) {
        allAssetsLoaded();
    }
}
function allAssetsLoaded() {
    //stop the bouncy ball
    elements.ball.classList.remove('bouncy');

    window.setTimeout(function() {
        //fade the ball screen away
        elements.loading.style.opacity = 0;
        elements.loading.addEventListener('transitionend', showHomeScreen, false);
    }, 500);
}
function showHomeScreen() {
    elements.loading.removeEventListener('transitionend', showHomeScreen, false);
    elements.loading.classList.add('hidden');
    elements.opening.classList.remove('hidden');
    //the fadeIn wasn't happening, it's all too fast
    window.setTimeout(function() {
        elements.opening.style.opacity = 1;
    }, 100);
}

function endGameMessage() {
    var t = game.total;
    var message, which, rank;
    if (t > 200) {
        rank = 2;
    } else if (t > 60 && t <= 200) {
        rank = 1;
    } else if (t <= 60) {
        rank = 0;
    }
    which = Math.floor(Math.random() * endMessages[rank].length);
    message = endMessages[rank][which];
    console.log(message);
    return message;
}

<commit_msg>edited threshold for end message score rankings<commit_after>function init() {
    var r1 = init_screens();

    if (r1) {
        init_loadingImages();
        init_info();
    } else {
        // console.log('poop');
        //can't play, stoppppp
        uponFailure();
    }
}

init();

function init_screens() {
    //screen sizes
    var wx = window.innerWidth,
        wy = window.innerHeight;
    library.scr[0] = wx;
    library.scr[1] = wy;
    library.canvas[0] = wx;
    library.canvas[1] = wy;
    var m;
    if (wx < 400) {
        m = 0.75;
    } else if (wx >= 400 && wx < 1000) {
        m = 1.25;
    } else if (wx >= 1000 && wx < 1600) {
        m = 1.5;
    } else if (wx >= 1600) {
        m = 2;
    } else {
        m = 1;
    }
    library.multiplier = m;

    //set the message position
    elements.message.style.top = library.scr[1] * 0.45 + 'px';

    //test out canvas capability
    elements.c = elements.canvas.getContext('2d');
    var result;
    if (elements.c !== null) {
        elements.canvas.setAttribute('height', library.canvas[1]);
        elements.canvas.setAttribute('width', library.canvas[0]);
        result = true;
    } else {
        //we can't play this game, tell the person to update browser
        library.data.poop = true;
        result = false;
    }
    return result;
}

function init_loadingImages() {
    var assets = [library.pim, library.magic, library.portal, library.poof, library.skull, library.bg, library.excla];
    var music = [library.ghost_sound, library.zombie_sound, library.transform_sound, library.portal_sound, library.player_sound];
    library.pim.src = 'images/pimsheet.svg';
    library.magic.src = 'images/magic.svg';
    library.portal.src = 'images/portal.svg';
    library.poof.src = 'images/poof.svg';
    library.skull.src = 'images/skull.svg';
    library.bg.src = 'images/background.jpg';
    library.excla.src = 'images/exclamation.svg';

    library.ghost_sound.src = 'track/Ghost_01.wav';
    library.zombie_sound.src = 'track/Action-02.wav';
    library.transform_sound.src = 'track/Powerup_01.wav';
    library.portal_sound.src = 'track/Portal-01.wav';
    library.player_sound.src = 'track/Function-Change-01.wav';

    for (var i = 0; i < assets.length; i++) {
        assets[i].addEventListener('load', finishedLoading, false);
    }
    for (var j = 0; j < music.length; j++) {
        music[j].addEventListener('canplay', finishedLoading, false);
    }
}

function init_info() {
    //check localStorage
    checkLocalStorage();

    //set the player action
    var playerRandom = Math.floor(Math.random() * 3);
    game.player = library.data.player[playerRandom];
    // console.log('the initial action is: ' + game.player);
    elements.player_action.textContent = game.player;

    //add functionality to opening screen
    prepareScreen();

    //add sound control to the info context
    elements.music.addEventListener('click', toggleSound, false);
}

function prepareScreen() {
    //event listeners
    elements.play.addEventListener('click', goToGame, false);
    elements.open_tutorial.addEventListener('click', accessTutorial, false);
}
function goToGame() {
    //hide opening, show game
    elements.opening.style.opacity = 0;
    elements.opening.addEventListener('transitionend', goToGameScreen, false);
}
function goToGameScreen() {
    elements.opening.removeEventListener('transitionend', goToGameScreen, false);
    elements.opening.classList.add('hidden');
    elements.game.classList.remove('hidden');
    window.setTimeout(function() {
        elements.game.style.opacity = 1;
        elements.game.addEventListener('transitionend', prepGame, false);
    }, 100);
}
function prepGame() {
    console.log('the game should be starting');
    elements.game.removeEventListener('transitionend', prepGame, false);
    message('get ready', 2500);
    //start game
    window.setTimeout( function() {
        message('go!', 750);
        game_start();
    }, 3000);
}

function game_start() {
    //clean everything up
    elements.c.clearRect(0, 0, library.canvas[0], library.canvas[1]);
    elements.c.globalAlpha = 1;
    reset_game_info('game');

    //start the time
    game.start = new Date();
    game.running = true;
    initCreate();

    //start the intervals
    game.player_loop = window.setInterval(player_change_action, 5000);
    game.loop = window.setInterval(gameUpdate, 100);

    //add event listeners
    elements.help_button.addEventListener('click', showHelp, false);
    elements.canvas.addEventListener('click', pushPim, false);
}
function reset_game_info(forwhat) {
    game.start = 0;
    game.end = 0;
    game.total = 0;
    game.score = 0;

    game.running = false;
    game.finished = false;

    if (forwhat === 'tutorial') {
        game.pims.length = 0;
        game.skulls.length = 0;
        game.magic.length = 0;

        game.limit[0] = 1;
        game.limit[1] = 0;
        game.limit[2] = 0;
    } else {
        //it's for the game
        game.round = library.data.rounds;
        game.pims.length = 0;
        game.skulls.length = 0;
        game.magic.length = 0;

        game.limit[0] = game.round + 3;
        game.limit[1] = game.round + 3;
        game.limit[2] = Math.floor(Math.random() * 5) + game.round * 2 + 10;
    }

    window.clearInterval(game.loop);
    window.clearInterval(game.player_loop);
    game.player = library.data.player[Math.floor(Math.random() * 3)];
}
function roundOver() {
    //congratulations!

    //stop things that need to be stopped
    game.running = false;
    game.finished = true;
    window.clearInterval(game.player_loop);
    elements.canvas.removeEventListener('click', pushPim, false);

    //what's our ending info?
    game.end = new Date();
    //take into account the saved time from pauses later
    var total = (game.end.getTime() - game.start.getTime()) / 1000 / 60;
    game.total += total;

    library.data.rounds++;
    var score = ( library.data.rounds * ((game.limit[0] / 3) + 3) * 1000 ) - (total * 60 * 2);
    score = Math.round(score);
    game.score = score;
    checkHighscore(score);

    showEnd();
}

//other stuff
function checkHighscore(num) {
    if (num && num > library.data.highscore) {
        library.data.highscore = num;
        window.localStorage['pimbo'] = num;
    }
}
function checkLocalStorage() {
    //does the localStorage exist?
    if (window.localStorage['pimbo']) {
        var hs = Number(window.localStorage['pimbo']);
        library.data.highscore = hs;
        elements.highscore_open.textContent = hs;
        elements.highscore_open.parentElement.classList.remove('hidden');
    } else {
        window.localStorage.setItem('pimbo', 0);
    }
}

function showHelp() {
    //pause game
    game.running = false;
    window.clearInterval(game.loop);
    window.clearInterval(game.player_loop);

    //note the time
    game.end = new Date();

    var total = (game.end.getTime() - game.start.getTime()) / 1000 / 60;
    game.total += total;

    //update help info
    updateHelpInfo();

    //show the help
    elements.info.classList.remove('hidden');
    window.setTimeout( function() {
        elements.info.style.opacity = 1;
    }, 100);
    elements.help_button.classList.remove('helphover');

    //event listeners
    elements.canvas.removeEventListener('click', pushPim, false);
    elements.help_button.removeEventListener('click', showHelp, false);
    elements.info_close.addEventListener('click', hideHelp, false);
}
function updateHelpInfo() {
    var hs;
    var prettyTime = Math.floor(game.total) + ':';
    prettyTime += 60 * (1 - (Math.ceil(game.total) - game.total));

    elements.info_round.textContent = library.data.rounds + 1;
    elements.info_time.textContent = Math.round(game.total * 60)+ ' seconds';

    if (library.data.highscore) {
        hs = library.data.highscore;
    } else {
        hs = 'noop';
    }
    elements.highscore_info.textContent = hs;
}
function hideHelp() {
    //hide the help
    elements.info.style.opacity = 0;

    //evnt listeners and stuff
    elements.help_button.classList.add('helphover');
    elements.info_close.removeEventListener('click', hideHelp, false);
    elements.info.addEventListener('transitionend', startGameAgain, false);

}
function startGameAgain() {
    elements.info.removeEventListener('transitionend', startGameAgain, false);
    elements.info.classList.add('hidden');

    window.setTimeout( function() {
        //start the game again
        game.running = true;
        game.start = new Date();
        game.player_loop = window.setInterval(player_change_action, 5000);
        game.loop = window.setInterval(gameUpdate, 100);

        //add event listeners
        elements.help_button.addEventListener('click', showHelp, false);
        elements.canvas.addEventListener('click', pushPim, false);

    }, 200);
}

function showEnd() {
    //update ending info

    elements.end_message.textContent = endGameMessage();
    elements.end_ghosts.textContent = game.limit[0] + ' pims';
    elements.end_time.textContent = Math.round(game.total * 60) + ' seconds';
    elements.end_score.textContent = game.score;
    elements.highscore_end.textContent = library.data.highscore;
    elements.highscore_end.parentElement.classList.remove('hidden');

    //show the end
    elements.help_button.classList.remove('helphover');
    elements.ending.classList.remove('hidden');
    window.setTimeout(function() {
        elements.ending.style.opacity = 1;
    }, 500);

    //event listeners
    elements.canvas.removeEventListener('click', pushPim, false);
    elements.help_button.removeEventListener('click', showHelp, false);
    elements.play_again.addEventListener('click', playAgain, false);
}
function playAgain() {
    //hide the ending
    elements.ending.style.opacity = 0;
    elements.ending.addEventListener('transitionend', showGameScreenAgain, false);
}
function showGameScreenAgain() {
    this.removeEventListener('transitionend', showGameScreenAgain, false);
    elements.ending.classList.add('hidden');

    //event listeners
    elements.play_again.removeEventListener('click', playAgain, false);
    elements.canvas.addEventListener('click', pushPim, false);
    elements.help_button.addEventListener('click', showHelp, false);
    elements.help_button.classList.add('helphover');

    message('get ready', 2000);
    window.setTimeout(function() {
        game_start();
        message('go!', 500);
    }, 2000);

}

function message(str, t) {
    //add a message to the screen
    elements.message.textContent = str;

    //show the message
    elements.message.classList.remove('hidden');

    //hide if after how many seconds?
    window.setTimeout( function() {
        elements.message.classList.add('hidden');
    }, t);
}

function toggleSound() {
    if (library.data.music) {
        library.data.music = false;
        elements.music.textContent = 'sound is off';
    } else {
        library.data.music = true;
        elements.music.textContent = 'sound is on';
    }
}

function uponFailure() {
    var fail = document.createElement('p');
    fail.innerHTML = 'Sorry, this browser does not support canvas. You need canvas to play this game. Please consider another browser for your gaming pleasure.';
    elements.loading.appendChild(fail);
}

function finishedLoading() {
    // console.log(this + ' finished loading');
    this.volume *= 0.45;
    this.removeEventListener('load', finishedLoading, false);
    library.assetsLoaded++;

    if (library.assetsLoaded === library.totalAssets) {
        allAssetsLoaded();
    }
}
function allAssetsLoaded() {
    //stop the bouncy ball
    elements.ball.classList.remove('bouncy');

    window.setTimeout(function() {
        //fade the ball screen away
        elements.loading.style.opacity = 0;
        elements.loading.addEventListener('transitionend', showHomeScreen, false);
    }, 500);
}
function showHomeScreen() {
    elements.loading.removeEventListener('transitionend', showHomeScreen, false);
    elements.loading.classList.add('hidden');
    elements.opening.classList.remove('hidden');
    //the fadeIn wasn't happening, it's all too fast
    window.setTimeout(function() {
        elements.opening.style.opacity = 1;
    }, 100);
}

function endGameMessage() {
    var t = game.total;
    var message, which, rank;
    if (t > 120) {
        rank = 2;
    } else if (t > 30 && t <= 120) {
        rank = 1;
    } else if (t <= 30) {
        rank = 0;
    }
    which = Math.floor(Math.random() * endMessages[rank].length);
    message = endMessages[rank][which];
    console.log(message);
    return message;
}

<|endoftext|>


<commit_before>(function() {
    function $ify(el) {
        if (!el) {
            return el;
        }

        el.appendText = function(text) {
            const lines = text.split(/\r?\n/);
            let first = true;

            lines.forEach(function(line) {
                if (first) {
                    first = false;
                } else {
                    el.appendChild(document.createElement('br'));
                }

                el.appendChild(document.createTextNode(line));
            });

            return el;
        };

        el.append = function() {
            for (let i = 0; i < arguments.length; ++i) {
                if (typeof(arguments[i]) === 'string') {
                    el.appendText(arguments[i]);
                } else {
                    el.appendChild(arguments[i]);
                }
            }

            return el;
        };

        el.clearChildren = function() {
            while (el.firstChild) {
                el.removeChild(el.firstChild);
            }

            return el;
        };

        return el;
    }

    // $(arg, [attributes,] [child, [child, [...]]])
    function $(arg) {
        if (arg.slice(0, 1) == '.') {
            return Array.from(document.getElementsByClassName(arg.slice(1))).map($ify);
        } else if (arg.slice(0, 1) == '#') {
            return $ify(document.getElementById(arg.slice(1)));
        }

        const el = document.createElement(arg);

        for (let i = 1; i < arguments.length; ++i) {
            const obj = arguments[i];

            if (obj) {
                if ((typeof(obj) === 'object') && !(obj instanceof Element) && !obj.append) {
                    Object.keys(obj).forEach(function(key) {
                        el.setAttribute(key, obj[key]);
                    });
                } else {
                    el.append(obj);
                }
            }
        }

        return el;
    }

    function arraysEqual(a, b) {
        if (!a && !b) {
            return true;
        }

        if (!a || !b || a.length !== b.length) {
            return false;
        }

        for (let i = 0; i < a.length; ++i) {
            if (a[i] !== b[i]) {
                return false;
            }
        }

        return true;
    }

    function getHash() {
        return decodeURI(location.hash.slice(1).toLowerCase());
    }

    // Fade all children of el out and then run callback
    function fadeChildrenOutAndThen(el, callback) {
        if (el.childNodes.length === 0) {
            callback();
            return;
        }

        // Fade out animation length is constant, so it's fine to just call it on the first element's animationend
        let callbackSet = false;

        for (let i = 0; i < el.childNodes.length; ++i) {
            if (!callbackSet) {
                el.childNodes[i].addEventListener('animationend', function() {
                    el.clearChildren();
                    callback();
                });

                callbackSet = true;
            }

            el.childNodes[i].classList.add('fade-out');
        }
    }

    function setSecretMessage(message) {
        const span = $('#secret-message');

        if (message.length > 0) {
            span.clearChildren();
            span.append(' | ' + message);
        } else {
            span.clearChildren();
        }
    }

    function ContentContainer(el) {
        const contentContainer = {
            'catModeOn': false,
            'currentTitlesShown': null,
            'el': el,
            'titles': [],
            'replaceWith': function() {
                this.currentTitlesShown = null;
                const els = arguments;

                fadeChildrenOutAndThen(el, function() {
                    for (let i = 0; i < els.length; ++i) {
                        el.append(els[i]);
                    }
                });
            },
            'showHelp': function() {
                this.replaceWith(
                    $('h2', 'Search for a title using the box to the right of the logo.'),
                    $('ul',
                        $('li', 'Type part of a title or type the title number.'),
                        $('li', 'Click ', $('span', { 'class': 'copy-link' }, '/title #'), ' to copy.'),
                        $('li', 'The links below the logo will show you titles in that category.')
                    ),
                    $('p', 'There might be a few hidden features, as well.')
                );
            },
            'showCredits': function() {
                this.replaceWith(
                    $('h2', 'Creator'),
                    $('p', 'Dedax'),
                    $('h2', 'Banner'),
                    $('p', 'Jacobmood'),
                    $('h2', 'Icons'),
                    $('p', 'EmojiOne 2.0'),
                    $('h2', 'Suggestions from'),
                    $('p', 'Elizalove, Levelup, Epilepsy, Imaginist')
                );
            },
            'showAllTitles': function() {
                this.showTitles(this.titles);
            },
            'showRandomTitle': function() {
                const idx = Math.floor(Math.random() * this.titles.length);
                this.showTitles(this.titles.slice(idx, idx + 1));
            },
            'showMatches': function(query) {
                query = query.toLowerCase().trim();

                if (query === '' || (query.length < 2) && isNaN(query)) {
                    setSecretMessage('');
                    return;
                }

                if (query === atob('YnV0dHM=')) {
                    document.body.classList.add('zoop');
                } else if (query === atob('YW15')) {
                    if (!$('#m')) {
                        this.replaceWith(
                            $('span', { 'id': 'm' }, $('span', { 'id': 'n' }))
                        );
                    }
                    return;
                }

                if (this.secrets && this.secrets[query]) {
                    setSecretMessage(this.secrets[query]);
                } else {
                    setSecretMessage('');
                }

                const matches = this.titles.filter(function(title) {
                    return (
                        title.name.toLowerCase().includes(query) ||
                        (title.altName && title.altName.toLowerCase().includes(query)) ||
                        title.id.toString().includes(query)
                    );
                });

                this.showTitles(matches);
            },
            'showTag': function(tag) {
                const matches = this.titles.filter(function(title) {
                    return title.tags.includes(tag);
                });

                this.showTitles(matches);
            },
            'showTitles': function(titles) {
                if (titles.length === 0) {
                    if (this.currentTitlesShown.length === 0) {
                        return;
                    }

                    this.replaceWith($('p', 'Nobody here but us chickens...'));
                    this.currentTitlesShown = [];
                    return;
                }

                if (arraysEqual(titles, this.currentTitlesShown)) {
                    return;
                }

                const titleSections = [];

                titles.forEach(function(title) {
                    const titleSection = $('section');
                    const copySpan = $('span',
                        {
                            'class': 'copy-span'
                        },
                        $('a',
                            {
                                'class': 'copy-link',
                                'href': '#',
                                'title': 'Click to copy'
                            },
                            '/title ' + title.id
                        )
                    );

                    copySpan.onclick = (function(copySpan) {
                        return function() {
                            // https://stackoverflow.com/a/987376
                            const rng = document.createRange();
                            rng.selectNodeContents(copySpan);

                            const sel = window.getSelection();
                            sel.removeAllRanges();
                            sel.addRange(rng);

                            document.execCommand('copy');

                            sel.removeAllRanges();

                            const popup = $('span',
                                {
                                    'class': 'popup'
                                },
                                'Copied'
                            );

                            popup.onanimationend = function() {
                                popup.parentNode.removeChild(popup);
                            };

                            copySpan.appendChild(popup);

                            return false;
                        };
                    })(copySpan, title.id);

                    let titleText = title.name;

                    if (title.altName) {
                        titleText = title.altName + ' / ' + titleText;
                    }

                    if (contentContainer.catModeOn) {
                        titleText = titleText.replace('Mouse', 'Cat')
                            .replace('mouse', 'cat')
                            .replace('Maus', 'Katze')
                            .replace('maus', 'katze')
                            .replace('Souris', 'Chat')
                            .replace('souris', 'chat');
                    }

                    titleSection.append(
                        $('p',
                            $('span', { 'class': 'title' }, titleText),
                            ' ',
                            copySpan
                        )
                    );

                    let description;

                    if (title.id === 138) {
                        description = $('a',
                            {
                                'href': 'http://www.youtube.com/watch?v=dQw4w9WgXcQ'
                            },
                            title.description
                        );
                    } else {
                        description = title.description;
                    }

                    titleSection.append(
                        $('p',
                            { 'class': 'title-description' },
                            description
                        )
                    );

                    titleSections.push(titleSection);
                });

                this.currentTitlesShown = titles;

                fadeChildrenOutAndThen(el, function() {
                    for (let i = 0; i < titleSections.length; ++i) {
                        el.append(titleSections[i]);
                    }
                });
            },
            'toggleCatMode': function() {
                this.catModeOn = !this.catModeOn;

                if (this.currentTitlesShown) {
                    this.showTitles(this.currentTitlesShown);
                }
            }
        };

        return contentContainer;
    }

    function navigate(content) {
        const hash = getHash();

        if (hash === 'credits') {
            content.showCredits();
        } else if (hash === 'all') {
            content.showAllTitles();
        } else if (hash === 'random') {
            content.showRandomTitle();
        } else if (hash.slice(0, 4) === 'tag/') {
            const tag = hash.slice(4);

            content.showTag(tag);
        } else {
            content.showHelp();
        }
    }

    function createFooter(content) {
        const footer = $('#footer');

        footer.append($('h2', 'Super cool links', $('span', { 'id': 'secret-message' } )));

        $('#header-link').onclick = function() {
            if (getHash() === 'help') {
                content.showHelp();
            }
        };

        const helpLink = $('a', { 'href': '#help' }, 'Help');
        const creditsLink = $('a', { 'href': '#credits' }, 'Credits');

        helpLink.onclick = function() {
            if (getHash() === 'help') {
                content.showHelp();
            }
        };

        creditsLink.onclick = function() {
            if (getHash() === 'credits') {
                content.showCredits();
            }
        };

        const links = $('ul');
        links.append($('li', $('a', { 'href': 'https://transformice.com/' }, 'transformice.com')));
        links.append($('li', $('a', { 'href': 'https://instagram.com/jegerniclas/' }, 'Creator\'s Instagram')));
        links.append($('li', helpLink));
        links.append($('li', creditsLink));
        links.append($('li', $('a', { 'href': 'https://github.com/xDeda/xdeda.github.io' }, 'GitHub Repository')));

        footer.append(links);

        // Add cat mode button
        const mouseIcon = 'mouse.png';
        const catIcon = 'cat.png';

        const catButton = $('img',
            {
                'src': mouseIcon,
                'alt': 'cat mode',
                'width': 32,
                'height': 32
            }
        );

        const catLink = $('a',
            {
                'href': '#',
                'id': 'cat-link'
            },
            catButton
        );

        catLink.onclick = function() {
            content.toggleCatMode();

            if (content.catModeOn) {
                catButton.src = catIcon;
            } else {
                catButton.src = mouseIcon;
            }

            return false;
        };

        footer.appendChild(catLink);
    }

    function loadData(content, listedTags) {
        const header = $('#header');
        const nav = $('#nav');

        // Add search box
        const searchInput = $('input',
            {
                'id': 'search',
                'type': 'text',
                'placeholder': 'search for title'
            }
        );

        let searchTimeoutId = null;

        function queueSearch(query) {
            clearTimeout(searchTimeoutId);

            searchTimeoutId = setTimeout(function() {
                content.showMatches(query);
            }, 250);
        }

        searchInput.addEventListener('keyup', function(event) {
            queueSearch(searchInput.value);
        });

        searchInput.addEventListener('paste', function() {
            queueSearch(searchInput.value);
        });

        header.insertBefore(searchInput, header.childNodes[2]);

        // Add links to tags
        function addLink(text, hash, onclick) {
            const link = $('a', { 'href': '#' + hash }, text);
            link.onclick = onclick;
            nav.append($('li', link));
        }

        addLink('All Titles', 'all', content.showAllTitles.bind(content));
        addLink('Random', 'random', content.showRandomTitle.bind(content));

        listedTags.forEach(function(tag) {
            addLink(tag, 'tag/' + tag.toLowerCase(), (function() {
                return function() {
                    content.showTag(tag.toLowerCase());
                };
            })(tag));
        });

        if (getHash() === '') {
            content.showHelp();
        } else {
            navigate(content);
        }
    }

    function init() {
        const content = ContentContainer($('#content'));

        window.onhashchange = function() {
            navigate(content);
        };

        content.replaceWith($('p', 'Loading...'));

        function showErrorMessage() {
            content.replaceWith(
                $('p', 'An error occurred while attempting to retrieve the titles. Please try refreshing the page.')
            );
        }

        createFooter(content);

        // Load title data
        const req = new XMLHttpRequest();

        req.onload = function() {
            if (req.status < 400) {
                let configParsed = false;
                let listedTags = [];

                try {
                    const config = JSON.parse(req.response);

                    content.titles = config.titles;
                    listedTags = config.listedTags;
                    content.secrets = config.secrets;

                    configParsed = true;
                } catch (e) {
                    showErrorMessage();
                }

                if (configParsed) {
                    loadData(content, listedTags);
                }
            } else {
                showErrorMessage();
            }
        };

        req.onerror = showErrorMessage;

        req.open('GET', 'config.json');
        req.send();
    }

    window.onload = init;
})();
<commit_msg>Remove 2 character minimum on searches<commit_after>(function() {
    function $ify(el) {
        if (!el) {
            return el;
        }

        el.appendText = function(text) {
            const lines = text.split(/\r?\n/);
            let first = true;

            lines.forEach(function(line) {
                if (first) {
                    first = false;
                } else {
                    el.appendChild(document.createElement('br'));
                }

                el.appendChild(document.createTextNode(line));
            });

            return el;
        };

        el.append = function() {
            for (let i = 0; i < arguments.length; ++i) {
                if (typeof(arguments[i]) === 'string') {
                    el.appendText(arguments[i]);
                } else {
                    el.appendChild(arguments[i]);
                }
            }

            return el;
        };

        el.clearChildren = function() {
            while (el.firstChild) {
                el.removeChild(el.firstChild);
            }

            return el;
        };

        return el;
    }

    // $(arg, [attributes,] [child, [child, [...]]])
    function $(arg) {
        if (arg.slice(0, 1) == '.') {
            return Array.from(document.getElementsByClassName(arg.slice(1))).map($ify);
        } else if (arg.slice(0, 1) == '#') {
            return $ify(document.getElementById(arg.slice(1)));
        }

        const el = document.createElement(arg);

        for (let i = 1; i < arguments.length; ++i) {
            const obj = arguments[i];

            if (obj) {
                if ((typeof(obj) === 'object') && !(obj instanceof Element) && !obj.append) {
                    Object.keys(obj).forEach(function(key) {
                        el.setAttribute(key, obj[key]);
                    });
                } else {
                    el.append(obj);
                }
            }
        }

        return el;
    }

    function arraysEqual(a, b) {
        if (!a && !b) {
            return true;
        }

        if (!a || !b || a.length !== b.length) {
            return false;
        }

        for (let i = 0; i < a.length; ++i) {
            if (a[i] !== b[i]) {
                return false;
            }
        }

        return true;
    }

    function getHash() {
        return decodeURI(location.hash.slice(1).toLowerCase());
    }

    // Fade all children of el out and then run callback
    function fadeChildrenOutAndThen(el, callback) {
        if (el.childNodes.length === 0) {
            callback();
            return;
        }

        // Fade out animation length is constant, so it's fine to just call it on the first element's animationend
        let callbackSet = false;

        for (let i = 0; i < el.childNodes.length; ++i) {
            if (!callbackSet) {
                el.childNodes[i].addEventListener('animationend', function() {
                    el.clearChildren();
                    callback();
                });

                callbackSet = true;
            }

            el.childNodes[i].classList.add('fade-out');
        }
    }

    function setSecretMessage(message) {
        const span = $('#secret-message');

        if (message.length > 0) {
            span.clearChildren();
            span.append(' | ' + message);
        } else {
            span.clearChildren();
        }
    }

    function ContentContainer(el) {
        const contentContainer = {
            'catModeOn': false,
            'currentTitlesShown': null,
            'el': el,
            'titles': [],
            'replaceWith': function() {
                this.currentTitlesShown = null;
                const els = arguments;

                fadeChildrenOutAndThen(el, function() {
                    for (let i = 0; i < els.length; ++i) {
                        el.append(els[i]);
                    }
                });
            },
            'showHelp': function() {
                this.replaceWith(
                    $('h2', 'Search for a title using the box to the right of the logo.'),
                    $('ul',
                        $('li', 'Type part of a title or type the title number.'),
                        $('li', 'Click ', $('span', { 'class': 'copy-link' }, '/title #'), ' to copy.'),
                        $('li', 'The links below the logo will show you titles in that category.')
                    ),
                    $('p', 'There might be a few hidden features, as well.')
                );
            },
            'showCredits': function() {
                this.replaceWith(
                    $('h2', 'Creator'),
                    $('p', 'Dedax'),
                    $('h2', 'Banner'),
                    $('p', 'Jacobmood'),
                    $('h2', 'Icons'),
                    $('p', 'EmojiOne 2.0'),
                    $('h2', 'Suggestions from'),
                    $('p', 'Elizalove, Levelup, Epilepsy, Imaginist')
                );
            },
            'showAllTitles': function() {
                this.showTitles(this.titles);
            },
            'showRandomTitle': function() {
                const idx = Math.floor(Math.random() * this.titles.length);
                this.showTitles(this.titles.slice(idx, idx + 1));
            },
            'showMatches': function(query) {
                query = query.toLowerCase().trim();

                if (this.secrets && this.secrets[query]) {
                    setSecretMessage(this.secrets[query]);
                } else {
                    setSecretMessage('');
                }

                if (query === atob('YnV0dHM=')) {
                    document.body.classList.add('zoop');
                } else if (query === atob('YW15')) {
                    if (!$('#m')) {
                        this.replaceWith(
                            $('span', { 'id': 'm' }, $('span', { 'id': 'n' }))
                        );
                    }
                    return;
                }

                const matches = this.titles.filter(function(title) {
                    return (
                        title.name.toLowerCase().includes(query) ||
                        (title.altName && title.altName.toLowerCase().includes(query)) ||
                        title.id.toString().includes(query)
                    );
                });

                this.showTitles(matches);
            },
            'showTag': function(tag) {
                const matches = this.titles.filter(function(title) {
                    return title.tags.includes(tag);
                });

                this.showTitles(matches);
            },
            'showTitles': function(titles) {
                if (titles.length === 0) {
                    if (this.currentTitlesShown.length === 0) {
                        return;
                    }

                    this.replaceWith($('p', 'Nobody here but us chickens...'));
                    this.currentTitlesShown = [];
                    return;
                }

                if (arraysEqual(titles, this.currentTitlesShown)) {
                    return;
                }

                const titleSections = [];

                titles.forEach(function(title) {
                    const titleSection = $('section');
                    const copySpan = $('span',
                        {
                            'class': 'copy-span'
                        },
                        $('a',
                            {
                                'class': 'copy-link',
                                'href': '#',
                                'title': 'Click to copy'
                            },
                            '/title ' + title.id
                        )
                    );

                    copySpan.onclick = (function(copySpan) {
                        return function() {
                            // https://stackoverflow.com/a/987376
                            const rng = document.createRange();
                            rng.selectNodeContents(copySpan);

                            const sel = window.getSelection();
                            sel.removeAllRanges();
                            sel.addRange(rng);

                            document.execCommand('copy');

                            sel.removeAllRanges();

                            const popup = $('span',
                                {
                                    'class': 'popup'
                                },
                                'Copied'
                            );

                            popup.onanimationend = function() {
                                popup.parentNode.removeChild(popup);
                            };

                            copySpan.appendChild(popup);

                            return false;
                        };
                    })(copySpan, title.id);

                    let titleText = title.name;

                    if (title.altName) {
                        titleText = title.altName + ' / ' + titleText;
                    }

                    if (contentContainer.catModeOn) {
                        titleText = titleText.replace('Mouse', 'Cat')
                            .replace('mouse', 'cat')
                            .replace('Maus', 'Katze')
                            .replace('maus', 'katze')
                            .replace('Souris', 'Chat')
                            .replace('souris', 'chat');
                    }

                    titleSection.append(
                        $('p',
                            $('span', { 'class': 'title' }, titleText),
                            ' ',
                            copySpan
                        )
                    );

                    let description;

                    if (title.id === 138) {
                        description = $('a',
                            {
                                'href': 'http://www.youtube.com/watch?v=dQw4w9WgXcQ'
                            },
                            title.description
                        );
                    } else {
                        description = title.description;
                    }

                    titleSection.append(
                        $('p',
                            { 'class': 'title-description' },
                            description
                        )
                    );

                    titleSections.push(titleSection);
                });

                this.currentTitlesShown = titles;

                fadeChildrenOutAndThen(el, function() {
                    for (let i = 0; i < titleSections.length; ++i) {
                        el.append(titleSections[i]);
                    }
                });
            },
            'toggleCatMode': function() {
                this.catModeOn = !this.catModeOn;

                if (this.currentTitlesShown) {
                    this.showTitles(this.currentTitlesShown);
                }
            }
        };

        return contentContainer;
    }

    function navigate(content) {
        const hash = getHash();

        if (hash === 'credits') {
            content.showCredits();
        } else if (hash === 'all') {
            content.showAllTitles();
        } else if (hash === 'random') {
            content.showRandomTitle();
        } else if (hash.slice(0, 4) === 'tag/') {
            const tag = hash.slice(4);

            content.showTag(tag);
        } else {
            content.showHelp();
        }
    }

    function createFooter(content) {
        const footer = $('#footer');

        footer.append($('h2', 'Super cool links', $('span', { 'id': 'secret-message' } )));

        $('#header-link').onclick = function() {
            if (getHash() === 'help') {
                content.showHelp();
            }
        };

        const helpLink = $('a', { 'href': '#help' }, 'Help');
        const creditsLink = $('a', { 'href': '#credits' }, 'Credits');

        helpLink.onclick = function() {
            if (getHash() === 'help') {
                content.showHelp();
            }
        };

        creditsLink.onclick = function() {
            if (getHash() === 'credits') {
                content.showCredits();
            }
        };

        const links = $('ul');
        links.append($('li', $('a', { 'href': 'https://transformice.com/' }, 'transformice.com')));
        links.append($('li', $('a', { 'href': 'https://instagram.com/jegerniclas/' }, 'Creator\'s Instagram')));
        links.append($('li', helpLink));
        links.append($('li', creditsLink));
        links.append($('li', $('a', { 'href': 'https://github.com/xDeda/xdeda.github.io' }, 'GitHub Repository')));

        footer.append(links);

        // Add cat mode button
        const mouseIcon = 'mouse.png';
        const catIcon = 'cat.png';

        const catButton = $('img',
            {
                'src': mouseIcon,
                'alt': 'cat mode',
                'width': 32,
                'height': 32
            }
        );

        const catLink = $('a',
            {
                'href': '#',
                'id': 'cat-link'
            },
            catButton
        );

        catLink.onclick = function() {
            content.toggleCatMode();

            if (content.catModeOn) {
                catButton.src = catIcon;
            } else {
                catButton.src = mouseIcon;
            }

            return false;
        };

        footer.appendChild(catLink);
    }

    function loadData(content, listedTags) {
        const header = $('#header');
        const nav = $('#nav');

        // Add search box
        const searchInput = $('input',
            {
                'id': 'search',
                'type': 'text',
                'placeholder': 'search for title'
            }
        );

        let searchTimeoutId = null;

        function queueSearch(query) {
            clearTimeout(searchTimeoutId);

            searchTimeoutId = setTimeout(function() {
                content.showMatches(query);
            }, 250);
        }

        searchInput.addEventListener('keyup', function(event) {
            queueSearch(searchInput.value);
        });

        searchInput.addEventListener('paste', function() {
            queueSearch(searchInput.value);
        });

        header.insertBefore(searchInput, header.childNodes[2]);

        // Add links to tags
        function addLink(text, hash, onclick) {
            const link = $('a', { 'href': '#' + hash }, text);
            link.onclick = onclick;
            nav.append($('li', link));
        }

        addLink('All Titles', 'all', content.showAllTitles.bind(content));
        addLink('Random', 'random', content.showRandomTitle.bind(content));

        listedTags.forEach(function(tag) {
            addLink(tag, 'tag/' + tag.toLowerCase(), (function() {
                return function() {
                    content.showTag(tag.toLowerCase());
                };
            })(tag));
        });

        if (getHash() === '') {
            content.showHelp();
        } else {
            navigate(content);
        }
    }

    function init() {
        const content = ContentContainer($('#content'));

        window.onhashchange = function() {
            navigate(content);
        };

        content.replaceWith($('p', 'Loading...'));

        function showErrorMessage() {
            content.replaceWith(
                $('p', 'An error occurred while attempting to retrieve the titles. Please try refreshing the page.')
            );
        }

        createFooter(content);

        // Load title data
        const req = new XMLHttpRequest();

        req.onload = function() {
            if (req.status < 400) {
                let configParsed = false;
                let listedTags = [];

                try {
                    const config = JSON.parse(req.response);

                    content.titles = config.titles;
                    listedTags = config.listedTags;
                    content.secrets = config.secrets;

                    configParsed = true;
                } catch (e) {
                    showErrorMessage();
                }

                if (configParsed) {
                    loadData(content, listedTags);
                }
            } else {
                showErrorMessage();
            }
        };

        req.onerror = showErrorMessage;

        req.open('GET', 'config.json');
        req.send();
    }

    window.onload = init;
})();
<|endoftext|>


<commit_before>ROWS = 20;
COLS = 10;
BLACK = 0;
boardEl = document.getElementById("board");
board = [];
pieces = [
    [0, 0, 1, 0, 2, 0, 3, 0], // cyan I
    [0, 0, 1, 0, 2, 0, 2, 1], // blue J
    [0, 1, 1, 1, 2, 1, 2, 0], // orange L
    [1, 0, 1, 1, 2, 0, 2, 1], // yellow O
    [0, 1, 1, 1, 1, 0, 2, 0], // lime S
    [0, 0, 1, 0, 2, 0, 1, 1], // purple T
    [0, 0, 1, 0, 1, 1, 2, 1] // red Z
];
activePiece = null;
activeColor = BLACK;
interval = null;
for (var r = 0; r < ROWS; r++) {
    board[r] = [];
    for (var c = 0; c < COLS; c++) {
        board[r][c] = BLACK;
    }
}
function getCellColor(r, c) {
    if (activePiece != null) {
        for (var i = 0; i < activePiece.length; i += 2) {
            if (activePiece[i + 1] == r && activePiece[i] == c) {
                return activeColor;
            }
        }
    }
    return board[r][c];
}
function paint() {
    var content = "";
    for (var r = 0; r < ROWS; r++) {
        content += '
';
        for (var c = 0; c < COLS; c++) {
            content += '

';
        }
        content += "
";
    }
    boardEl.innerHTML = content;
}
function lock(piece, color) {
    for (var i = 0; i < piece.length; i += 2) {
        board[piece[i + 1]][piece[i]] = color;
    }
}
function move(piece, dx, dy) {
    for (var i = 0; i < piece.length; i++) {
        piece[i] += i % 2 ? dy : dx;
    }
}
function canMove(piece, dx, dy) {
    move(piece, dx, dy);
    var result = true;
    for (var i = 0; i < piece.length; i += 2) {
        var x = piece[i],
            y = piece[i + 1];
        if (x < 0 || x >= COLS) {
            result = false;
            break;
        }
        if (y < 0 || y >= ROWS) {
            result = false;
            break;
        }
        if (board[y][x] != BLACK) {
            result = false;
            break;
        }
    }
    move(piece, -dx, -dy);
    return result;
}
function tick() {
    var curr = activePiece;
    if (activePiece == null) {
        var activeIndex = Math.floor(Math.random() * pieces.length);
        curr = activePiece = pieces[activeIndex].slice();
        activeColor = activeIndex + 1;
        move(curr, 3, 0);
        if (! canMove(curr, 0, 0)) {
            boardEl.innerHTML = '
Game Over!
';
            clearInterval(interval);
            return;
        }
    } else {
        if (canMove(curr, 0, 1)) {
            move(curr, 0, 1); // move
        } else {
            lock(curr, activeColor);
            activePiece = null;
        }
    }
    paint();
}
document.addEventListener('keydown', function(event) {
    switch (event.code) {
        case 'ArrowLeft':
            console.log("left?");
            if (activePiece && canMove(activePiece, -1, 0)) {
                console.log("left");
                move(activePiece, -1, 0)
            }
            break;
        case 'ArrowRight':
            console.log("right?");
            if (activePiece && canMove(activePiece, 1, 0)) {
                console.log("right");
                move(activePiece, 1, 0)
            }
            break;
        default:
            console && console.log && console.log(event.code, "is ignored");
    }
});
interval = setInterval(tick, 200);
tick();
<commit_msg>removed the 'move' calls in canMove in favor of tweaking the temp var's values<commit_after>ROWS = 20;
COLS = 10;
BLACK = 0;
boardEl = document.getElementById("board");
board = [];
pieces = [
    [0, 0, 1, 0, 2, 0, 3, 0], // cyan I
    [0, 0, 1, 0, 2, 0, 2, 1], // blue J
    [0, 1, 1, 1, 2, 1, 2, 0], // orange L
    [1, 0, 1, 1, 2, 0, 2, 1], // yellow O
    [0, 1, 1, 1, 1, 0, 2, 0], // lime S
    [0, 0, 1, 0, 2, 0, 1, 1], // purple T
    [0, 0, 1, 0, 1, 1, 2, 1] // red Z
];
activePiece = null;
activeColor = BLACK;
interval = null;
for (var r = 0; r < ROWS; r++) {
    board[r] = [];
    for (var c = 0; c < COLS; c++) {
        board[r][c] = BLACK;
    }
}
function getCellColor(r, c) {
    if (activePiece != null) {
        for (var i = 0; i < activePiece.length; i += 2) {
            if (activePiece[i + 1] == r && activePiece[i] == c) {
                return activeColor;
            }
        }
    }
    return board[r][c];
}
function paint() {
    var content = "";
    for (var r = 0; r < ROWS; r++) {
        content += '
';
        for (var c = 0; c < COLS; c++) {
            content += '

';
        }
        content += "
";
    }
    boardEl.innerHTML = content;
}
function lock(piece, color) {
    for (var i = 0; i < piece.length; i += 2) {
        board[piece[i + 1]][piece[i]] = color;
    }
}
function move(piece, dx, dy) {
    for (var i = 0; i < piece.length; i++) {
        piece[i] += i % 2 ? dy : dx;
    }
}
function canMove(piece, dx, dy) {
    for (var i = 0; i < piece.length; i += 2) {
        var x = piece[i] + dx,
            y = piece[i + 1] + dy;
        if (x < 0 || x >= COLS) {
            return false;
        }
        if (y < 0 || y >= ROWS) {
            return false;
        }
        if (board[y][x] != BLACK) {
            return false;
        }
    }
    return true;
}
function tick() {
    var curr = activePiece;
    if (activePiece == null) {
        var activeIndex = Math.floor(Math.random() * pieces.length);
        curr = activePiece = pieces[activeIndex].slice();
        activeColor = activeIndex + 1;
        move(curr, 3, 0);
        if (! canMove(curr, 0, 0)) {
            boardEl.innerHTML = '
Game Over!
';
            clearInterval(interval);
            return;
        }
    } else {
        if (canMove(curr, 0, 1)) {
            move(curr, 0, 1); // move
        } else {
            lock(curr, activeColor);
            activePiece = null;
        }
    }
    paint();
}
document.addEventListener('keydown', function(event) {
    switch (event.code) {
        case 'ArrowLeft':
            console.log("left?");
            if (activePiece && canMove(activePiece, -1, 0)) {
                console.log("left");
                move(activePiece, -1, 0)
            }
            break;
        case 'ArrowRight':
            console.log("right?");
            if (activePiece && canMove(activePiece, 1, 0)) {
                console.log("right");
                move(activePiece, 1, 0)
            }
            break;
        default:
            console && console.log && console.log(event.code, "is ignored");
    }
});
interval = setInterval(tick, 200);
tick();
<|endoftext|>