<commit_before>var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    alphabetButtonArray,
    wordToSearch = "",
    wordArray = [],
    checkedLetters = "",
    button,
    errors = 0,
    displayedWord,
    description,
    descriptionWord,
    letter,
    buttonText,
    message,
    guessButton,
    guessButtonText,
    lettersStat,
    guessedLetters,
    triedLetters,
    wrongLetters;

var GameState = {
    preload: function () {
        this.load.image("hangingMan0", "assets/images/0.png");
        this.load.image("hangingMan1", "assets/images/1.png");
        this.load.image("hangingMan2", "assets/images/2.png");
        this.load.image("hangingMan3", "assets/images/3.png");
        this.load.image("hangingMan4", "assets/images/4.png");
        this.load.image("hangingMan5", "assets/images/5.png");
        this.load.image(constants.buttonImageName, "assets/images/button.png");

    },

    create: function () {
        errors = 0;
        triedLetters = "";
        wrongLetters = "";
        alphabetButtonArray = [];
        stats = JSON.parse(localStorage.getItem(constants.localStorageStatsName)) || stats;
        this.game.stage.backgroundColor = constants.whiteColor;
        this.game.add.text(0, 0, constants.playedGamesText + stats.playedGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.wonGamesCoordinate, constants.wonGamesText + stats.wonGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.lostGamesCoordinate, constants.lostGamesText + stats.lostGames, { fontSize: constants.smallText });
        guessButton = this.game.add.button(constants.guessWordX, constants.guessWordY, constants.buttonImageName, function () {
            game.state.states.GameState.destroyGuessButton();
            var container = document.getElementById("container");
            var input = document.createElement("input");
            input.setAttribute("type", "text");
            input.setAttribute("id", "wordInput");
            container.appendChild(input);
            input.focus();
            game.input.keyboard.onDownCallback = function (e) {
                if (e.keyCode == constants.enterKey) {
                    var input = document.getElementById("wordInput");
                    var word = input.value;
                    input.remove();

                    if (word.toUpperCase() == wordToSearch) {
                        stats.guessedWords++;
                        stats.playedGames++;
                        stats.wonGames++;
                        game.state.states.GameState.revealWord();

                        var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });

                        win.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    } else {
                        stats.playedGames++;
                        stats.lostGames++;
                        var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });

                        lose.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    }
                }
            };
        });
        guessButton.scale.setTo(0.6, 1);
        guessButton.anchor.x = 0.5;
        guessButtonText = this.game.add.text(constants.guessWordX, constants.guessWordY + constants.buttonTextModifier, constants.guessWordText);
        guessButtonText.anchor.x = 0.5;
        lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });
        this.game.add.text(0, constants.guessedWordsCoordinate, constants.guessedWordsText + stats.guessedWords, { fontSize: constants.smallText });
        guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
        message = this.game.add.text();
        message.anchor.x = 0.5;
        this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan0");
        this.hangingMan.anchor.x = 0.5;
        this.game.input.keyboard.enabled = true;
        this.game.input.keyboard.onDownCallback = function (e) {
            if (e.keyCode >= constants.aKey && e.keyCode <= constants.zKey) {
                letter = String.fromCharCode(e.keyCode);
                game.state.states.GameState.checkMatch(letter);
            }
        };

        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
        description = this.game.add.text(game.world.centerX, constants.descriptionCoordinate, descriptionWord, { fontSize: constants.smallText });
        description.anchor.x = 0.5;
        this.addAlphabet();
    },

    update: function () {
    },

    init: function (selectedWord) {
        wordToSearch = selectedWord.word.toUpperCase();
        descriptionWord = selectedWord.description;

        var words = selectedWord.word.split(" "),
            hiddenWord = [],
            word,
            length;

        for (let i = 0; i < words.length; i++) {
            if (i > 0) {
                wordArray.push(" ");
            }

            word = words[i].toUpperCase();
            length = word.length;
            hiddenWord = new Array(length).fill("_");
            hiddenWord[0] = word.charAt(0);
            hiddenWord[length - 1] = word.charAt(length - 1);
            hiddenWord.forEach(char => {
                wordArray.push(char);
            }, this);
        }
    },

    addAlphabet: function () {
        var x = 480;
        var y = 120;
        for (var i = 0; i < alphabet.length; i++) {
            var letter = alphabet[i]
            button = this.game.add.button(x, y, constants.buttonImageName, function (e) {
                this.scale.setTo(0.05, -0.5)
                var letter = alphabetButtonArray.indexOf(this);
                game.state.states.GameState.checkMatch(alphabet[letter]);
            });
            button.anchor.x = 0.5;
            button.anchor.y = 0.5;
            button.scale.setTo(0.05, 0.5);
            alphabetButtonArray.push(button);
            buttonText = this.game.add.text(x, y + 4, alphabet[i], { fontSize:constants.smallText });
            buttonText.anchor.x = 0.5;
            buttonText.anchor.y = 0.5;
            x += 30;
            if (i % 5 === 0 && i > 0) {
                y += 30;
                x = 480;
            }
        }
    },

    addButton: function (text) {
        button = this.game.add.button(game.world.centerX, constants.newGameButtonCoordinate, constants.buttonImageName, this.newGame);
        button.scale.setTo(0.5, 1);
        button.anchor.x = 0.5;
        buttonText = this.game.add.text(game.world.centerX, constants.newGameButtonCoordinate + constants.buttonTextModifier, text);
        buttonText.anchor.x = 0.5;
        this.game.input.keyboard.enabled = false;
    },

    newGame: function () {
        wordArray = [];
        localStorage.setItem(constants.localStorageStatsName, JSON.stringify(stats));
        this.game.state.start(constants.menuStateName);
    },

    destroyGuessButton: function () {
        guessButton.destroy();
        guessButtonText.destroy();
    },

    revealWord: function () {
        var wordLength = wordToSearch.length;
        for (var i = 0; i < wordLength; i++) {
            wordArray[i] = wordToSearch.charAt(i);
        }
        this.updateWord();
    },

    updateWord: function() {
        displayedWord.destroy();
        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
    },

    checkMatch: function (letter) {
        if (triedLetters.indexOf(letter) >= 0) {
            message.destroy();
            message = this.game.add.text(game.world.centerX, constants.messageCoordinates, constants.triedLetterMessage, { fontSize: constants.smallText });
            message.anchor.x = 0.5;
            this.game.time.events.add(constants.messageTimerTime, function () {
                message.destroy();
            });
        } else {
            triedLetters += letter;

            if (wordToSearch.indexOf(letter) >= 0) {
                var index = wordToSearch.indexOf(letter);
                while (index >= 0) {
                    wordArray[index] = wordToSearch.charAt(index);
                    index = wordToSearch.indexOf(letter, index + 1);
                }

                stats.guessedLetters++;
                lettersStat.destroy();
                lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });

                this.updateWord();

                if (wordArray.indexOf("_") < 0) {
                    stats.playedGames++;
                    stats.wonGames++;
                    game.state.states.GameState.destroyGuessButton();

                    var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    win.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }

            } else {
                errors++;
                wrongLetters += letter;
                guessedLetters.destroy();
                guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
                this.hangingMan.destroy();
                this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan" + errors);
                this.hangingMan.anchor.x = 0.5;

                if (errors == constants.maxErrors) {
                    stats.playedGames++;
                    stats.lostGames++;
                    game.state.states.GameState.destroyGuessButton();

                    var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    lose.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }
            }
        }
    }
};<commit_msg>remove alphabet on guess and finisehed game<commit_after>var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    alphabetButtonArray,
    alphabetTextArray,
    wordToSearch = "",
    wordArray = [],
    checkedLetters = "",
    button,
    errors = 0,
    displayedWord,
    description,
    descriptionWord,
    letter,
    buttonText,
    message,
    guessButton,
    guessButtonText,
    lettersStat,
    guessedLetters,
    triedLetters,
    wrongLetters;

var GameState = {
    preload: function () {
        this.load.image("hangingMan0", "assets/images/0.png");
        this.load.image("hangingMan1", "assets/images/1.png");
        this.load.image("hangingMan2", "assets/images/2.png");
        this.load.image("hangingMan3", "assets/images/3.png");
        this.load.image("hangingMan4", "assets/images/4.png");
        this.load.image("hangingMan5", "assets/images/5.png");
        this.load.image(constants.buttonImageName, "assets/images/button.png");

    },

    create: function () {
        errors = 0;
        triedLetters = "";
        wrongLetters = "";
        alphabetButtonArray = [];
        alphabetTextArray = [];
        stats = JSON.parse(localStorage.getItem(constants.localStorageStatsName)) || stats;
        this.game.stage.backgroundColor = constants.whiteColor;
        this.game.add.text(0, 0, constants.playedGamesText + stats.playedGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.wonGamesCoordinate, constants.wonGamesText + stats.wonGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.lostGamesCoordinate, constants.lostGamesText + stats.lostGames, { fontSize: constants.smallText });
        guessButton = this.game.add.button(constants.guessWordX, constants.guessWordY, constants.buttonImageName, function () {
            game.state.states.GameState.destroyGuessButton();
            game.state.states.GameState.destroyAlphabetButtons();
            var container = document.getElementById("container");
            var input = document.createElement("input");
            input.setAttribute("type", "text");
            input.setAttribute("id", "wordInput");
            container.appendChild(input);
            input.focus();
            game.input.keyboard.onDownCallback = function (e) {
                if (e.keyCode == constants.enterKey) {
                    var input = document.getElementById("wordInput");
                    var word = input.value;
                    input.remove();

                    if (word.toUpperCase() == wordToSearch) {
                        stats.guessedWords++;
                        stats.playedGames++;
                        stats.wonGames++;
                        game.state.states.GameState.revealWord();

                        var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });

                        win.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    } else {
                        stats.playedGames++;
                        stats.lostGames++;
                        var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });

                        lose.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    }
                }
            };
        });
        guessButton.scale.setTo(0.6, 1);
        guessButton.anchor.x = 0.5;
        guessButtonText = this.game.add.text(constants.guessWordX, constants.guessWordY + constants.buttonTextModifier, constants.guessWordText);
        guessButtonText.anchor.x = 0.5;
        lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });
        this.game.add.text(0, constants.guessedWordsCoordinate, constants.guessedWordsText + stats.guessedWords, { fontSize: constants.smallText });
        guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
        message = this.game.add.text();
        message.anchor.x = 0.5;
        this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan0");
        this.hangingMan.anchor.x = 0.5;
        this.game.input.keyboard.enabled = true;
        this.game.input.keyboard.onDownCallback = function (e) {
            if (e.keyCode >= constants.aKey && e.keyCode <= constants.zKey) {
                letter = String.fromCharCode(e.keyCode);
                game.state.states.GameState.checkMatch(letter);
            }
        };

        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
        description = this.game.add.text(game.world.centerX, constants.descriptionCoordinate, descriptionWord, { fontSize: constants.smallText });
        description.anchor.x = 0.5;
        this.addAlphabet();
    },

    update: function () {
    },

    init: function (selectedWord) {
        wordToSearch = selectedWord.word.toUpperCase();
        descriptionWord = selectedWord.description;

        var words = selectedWord.word.split(" "),
            hiddenWord = [],
            word,
            length;

        for (let i = 0; i < words.length; i++) {
            if (i > 0) {
                wordArray.push(" ");
            }

            word = words[i].toUpperCase();
            length = word.length;
            hiddenWord = new Array(length).fill("_");
            hiddenWord[0] = word.charAt(0);
            hiddenWord[length - 1] = word.charAt(length - 1);
            hiddenWord.forEach(char => {
                wordArray.push(char);
            }, this);
        }
    },

    addAlphabet: function () {
        var x = 480;
        var y = 120;
        for (var i = 0; i < alphabet.length; i++) {
            var letter = alphabet[i]
            button = this.game.add.button(x, y, constants.buttonImageName, function (e) {
                this.scale.setTo(0.05, -0.5)
                var letter = alphabetButtonArray.indexOf(this);
                game.state.states.GameState.checkMatch(alphabet[letter]);
            });
            button.anchor.x = 0.5;
            button.anchor.y = 0.5;
            button.scale.setTo(0.05, 0.5);
            alphabetButtonArray.push(button);
            buttonText = this.game.add.text(x, y + 4, alphabet[i], { fontSize:constants.smallText });
            buttonText.anchor.x = 0.5;
            buttonText.anchor.y = 0.5;
            alphabetTextArray.push(buttonText)
            x += 30;
            if (i % 5 === 0 && i > 0) {
                y += 30;
                x = 480;
            }
        }
    },

    addButton: function (text) {
        button = this.game.add.button(game.world.centerX, constants.newGameButtonCoordinate, constants.buttonImageName, this.newGame);
        button.scale.setTo(0.5, 1);
        button.anchor.x = 0.5;
        buttonText = this.game.add.text(game.world.centerX, constants.newGameButtonCoordinate + constants.buttonTextModifier, text);
        buttonText.anchor.x = 0.5;
        this.game.input.keyboard.enabled = false;
    },

    newGame: function () {
        wordArray = [];
        localStorage.setItem(constants.localStorageStatsName, JSON.stringify(stats));
        this.game.state.start(constants.menuStateName);
    },

    destroyGuessButton: function () {
        guessButton.destroy();
        guessButtonText.destroy();
    },

    destroyAlphabetButtons: function () {
        for (var i = 0; i < alphabetButtonArray.length; i++) {
            // this removes the callback function intead of removing the buttons, but I don't like it
            // alphabetButtonArray[i].onInputUp = alphabetButtonArray[i].onInputDown;
            alphabetButtonArray[i].destroy();
            alphabetTextArray[i].destroy();
        }
    },

    revealWord: function () {
        var wordLength = wordToSearch.length;
        for (var i = 0; i < wordLength; i++) {
            wordArray[i] = wordToSearch.charAt(i);
        }
        this.updateWord();
    },

    updateWord: function() {
        displayedWord.destroy();
        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
    },

    checkMatch: function (letter) {
        if (triedLetters.indexOf(letter) >= 0) {
            message.destroy();
            message = this.game.add.text(game.world.centerX, constants.messageCoordinates, constants.triedLetterMessage, { fontSize: constants.smallText });
            message.anchor.x = 0.5;
            this.game.time.events.add(constants.messageTimerTime, function () {
                message.destroy();
            });
        } else {
            triedLetters += letter;

            if (wordToSearch.indexOf(letter) >= 0) {
                var index = wordToSearch.indexOf(letter);
                while (index >= 0) {
                    wordArray[index] = wordToSearch.charAt(index);
                    index = wordToSearch.indexOf(letter, index + 1);
                }

                stats.guessedLetters++;
                lettersStat.destroy();
                lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });

                this.updateWord();

                if (wordArray.indexOf("_") < 0) {
                    stats.playedGames++;
                    stats.wonGames++;
                    game.state.states.GameState.destroyGuessButton();
                    game.state.states.GameState.destroyAlphabetButtons();

                    var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    win.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }

            } else {
                errors++;
                wrongLetters += letter;
                guessedLetters.destroy();
                guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
                this.hangingMan.destroy();
                this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan" + errors);
                this.hangingMan.anchor.x = 0.5;

                if (errors == constants.maxErrors) {
                    stats.playedGames++;
                    stats.lostGames++;
                    game.state.states.GameState.destroyGuessButton();
                    game.state.states.GameState.destroyAlphabetButtons();

                    var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    lose.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }
            }
        }
    }
};<|endoftext|>


<commit_before>var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    wordToSearch = "",
    wordArray = [],
    checkedLetters = "",
    button,
    errors = 0,
    displayedWord,
    description,
    letter,
    buttonText,
    message,
    lettersStat,
    guessedLetters,
    triedLetters,
    wrongLetters;

var GameState = {
    preload: function () {
        this.load.image("hangingMan0", "assets/images/0.png");
        this.load.image("hangingMan1", "assets/images/1.png");
        this.load.image("hangingMan2", "assets/images/2.png");
        this.load.image("hangingMan3", "assets/images/3.png");
        this.load.image("hangingMan4", "assets/images/4.png");
        this.load.image("hangingMan5", "assets/images/5.png");
        this.load.image(constants.buttonImageName, "assets/images/button.png");

    },

    create: function () {
        errors = 0;
        triedLetters = "";
        wrongLetters = "";
        stats = JSON.parse(localStorage.getItem(constants.localStorageStatsName)) || stats;
        this.game.stage.backgroundColor = constants.whiteColor;
        this.game.add.text(0, 0, constants.playedGamesText + stats.playedGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.wonGamesCoordinate, constants.wonGamesText + stats.wonGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.lostGamesCoordinate, constants.lostGamesText + stats.lostGames, { fontSize: constants.smallText });
        button = this.game.add.button(constants.guessWordX, constants.guessWordY, constants.buttonImageName, function () {
            var container = document.getElementById("container");
            var input = document.createElement("input");
            input.setAttribute("type", "text");
            input.setAttribute("id", "wordInput");
            container.appendChild(input);
            input.focus();
            game.input.keyboard.onDownCallback = function (e) {
                if (e.keyCode == constants.enterKey) {
                    var input = document.getElementById("wordInput");
                    var word = input.value;
                    input.remove();

                    if (word.toUpperCase() == wordToSearch) {
                        stats.guessedWords++;
                        stats.playedGames++;
                        stats.wonGames++;
                        var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });
                        win.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    } else {
                        stats.playedGames++;
                        stats.lostGames++;
                        var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });
                        lose.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    }
                }
            };
        });
        button.scale.setTo(0.6, 1);
        button.anchor.x = 0.5;
        buttonText = this.game.add.text(constants.guessWordX, constants.guessWordY + constants.buttonTextModifier, constants.guessWordText);
        buttonText.anchor.x = 0.5;
        lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });
        this.game.add.text(0, constants.guessedWordsCoordinate, constants.guessedWordsText + stats.guessedWords, { fontSize: constants.smallText });
        guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
        message = this.game.add.text();
        message.anchor.x = 0.5;
        this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan0");
        this.hangingMan.anchor.x = 0.5;
        this.game.input.keyboard.enabled = true;
        this.game.input.keyboard.onDownCallback = function (e) {
            if (e.keyCode >= constants.aKey && e.keyCode <= constants.zKey) {
                letter = String.fromCharCode(e.keyCode);
                game.state.states.GameState.checkMatch(letter);
            }
        };
    },

    update: function () {
    },

    init: function (selectedWord) {
        wordToSearch = selectedWord.word.toUpperCase();

        var words = selectedWord.word.split(" "),
            hiddenWords = [],
            hiddenWord = [],
            word,
            length;

        for (let i = 0; i < words.length; i++) {
            if (i > 0) {
                wordArray.push(" ");
            }

            word = words[i].toUpperCase();
            length = word.length;
            hiddenWord = new Array(length).fill("_");
            hiddenWord[0] = word.charAt(0);
            hiddenWord[length - 1] = word.charAt(length - 1);
            hiddenWord.forEach(char => {
                wordArray.push(char);
            }, this);

            hiddenWords.push(hiddenWord.join(" "));
        }

        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
        description = this.game.add.text(game.world.centerX, constants.descriptionCoordinate, selectedWord.description, { fontSize: constants.smallText });
        description.anchor.x = 0.5;
    },

    addButton: function (text) {
        button = this.game.add.button(game.world.centerX, constants.newGameButtonCoordinate, constants.buttonImageName, this.newGame);
        button.scale.setTo(0.5, 1);
        button.anchor.x = 0.5;
        buttonText = this.game.add.text(game.world.centerX, constants.newGameButtonCoordinate + constants.buttonTextModifier, text);
        buttonText.anchor.x = 0.5;
        this.game.input.keyboard.enabled = false;
    },

    newGame: function () {
        wordArray = [];
        localStorage.setItem(constants.localStorageStatsName, JSON.stringify(stats));
        this.game.state.start(constants.menuStateName);
    },

    checkMatch: function (letter) {
        if (triedLetters.indexOf(letter) >= 0) {
            message.destroy();
            message = this.game.add.text(game.world.centerX, constants.messageCoordinates, constants.triedLetterMessage, { fontSize: constants.smallText });
            message.anchor.x = 0.5;
            this.game.time.events.add(constants.messageTimerTime, function () {
                message.destroy();
            });
        } else {
            triedLetters += letter;

            if (wordToSearch.indexOf(letter) >= 0) {
                var index = wordToSearch.indexOf(letter);
                while (index >= 0) {
                    wordArray[index] = wordToSearch.charAt(index);
                    index = wordToSearch.indexOf(letter, index + 1);
                }

                stats.guessedLetters++;
                lettersStat.destroy();
                lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });

                displayedWord.destroy();
                displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
                displayedWord.anchor.x = 0.5;

                if (wordArray.indexOf("_") < 0) {
                    stats.playedGames++;
                    stats.wonGames++;
                    var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    win.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }

            } else {
                errors++;
                wrongLetters += letter;
                guessedLetters.destroy();
                guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
                this.hangingMan.destroy();
                this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan" + errors);
                this.hangingMan.anchor.x = 0.5;

                if (errors == constants.maxErrors) {
                    stats.playedGames++;
                    stats.lostGames++;
                    var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    lose.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }
            }
        }
    }
};<commit_msg>revealing word after guess<commit_after>var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
    wordToSearch = "",
    wordArray = [],
    checkedLetters = "",
    button,
    errors = 0,
    displayedWord,
    description,
    letter,
    buttonText,
    message,
    guessButton,
    guessButtonText,
    lettersStat,
    guessedLetters,
    triedLetters,
    wrongLetters;

var GameState = {
    preload: function () {
        this.load.image("hangingMan0", "assets/images/0.png");
        this.load.image("hangingMan1", "assets/images/1.png");
        this.load.image("hangingMan2", "assets/images/2.png");
        this.load.image("hangingMan3", "assets/images/3.png");
        this.load.image("hangingMan4", "assets/images/4.png");
        this.load.image("hangingMan5", "assets/images/5.png");
        this.load.image(constants.buttonImageName, "assets/images/button.png");

    },

    create: function () {
        errors = 0;
        triedLetters = "";
        wrongLetters = "";
        stats = JSON.parse(localStorage.getItem(constants.localStorageStatsName)) || stats;
        this.game.stage.backgroundColor = constants.whiteColor;
        this.game.add.text(0, 0, constants.playedGamesText + stats.playedGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.wonGamesCoordinate, constants.wonGamesText + stats.wonGames, { fontSize: constants.smallText });
        this.game.add.text(0, constants.lostGamesCoordinate, constants.lostGamesText + stats.lostGames, { fontSize: constants.smallText });
        guessButton = this.game.add.button(constants.guessWordX, constants.guessWordY, constants.buttonImageName, function () {
            game.state.states.GameState.destroyGuessButton();
            var container = document.getElementById("container");
            var input = document.createElement("input");
            input.setAttribute("type", "text");
            input.setAttribute("id", "wordInput");
            container.appendChild(input);
            input.focus();
            game.input.keyboard.onDownCallback = function (e) {
                if (e.keyCode == constants.enterKey) {
                    var input = document.getElementById("wordInput");
                    var word = input.value;
                    input.remove();

                    if (word.toUpperCase() == wordToSearch) {
                        stats.guessedWords++;
                        stats.playedGames++;
                        stats.wonGames++;
                        game.state.states.GameState.revealWord();

                        var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });

                        win.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    } else {
                        stats.playedGames++;
                        stats.lostGames++;
                        var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                            fontSize: constants.bigText, backgroundColor: constants.whiteColor
                        });

                        lose.anchor.x = 0.5;
                        game.state.states.GameState.addButton(constants.newGameText);
                    }
                }
            };
        });
        guessButton.scale.setTo(0.6, 1);
        guessButton.anchor.x = 0.5;
        guessButtonText = this.game.add.text(constants.guessWordX, constants.guessWordY + constants.buttonTextModifier, constants.guessWordText);
        guessButtonText.anchor.x = 0.5;
        lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });
        this.game.add.text(0, constants.guessedWordsCoordinate, constants.guessedWordsText + stats.guessedWords, { fontSize: constants.smallText });
        guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
        message = this.game.add.text();
        message.anchor.x = 0.5;
        this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan0");
        this.hangingMan.anchor.x = 0.5;
        this.game.input.keyboard.enabled = true;
        this.game.input.keyboard.onDownCallback = function (e) {
            if (e.keyCode >= constants.aKey && e.keyCode <= constants.zKey) {
                letter = String.fromCharCode(e.keyCode);
                game.state.states.GameState.checkMatch(letter);
            }
        };
    },

    update: function () {
    },

    init: function (selectedWord) {
        wordToSearch = selectedWord.word.toUpperCase();

        var words = selectedWord.word.split(" "),
            hiddenWords = [],
            hiddenWord = [],
            word,
            length;

        for (let i = 0; i < words.length; i++) {
            if (i > 0) {
                wordArray.push(" ");
            }

            word = words[i].toUpperCase();
            length = word.length;
            hiddenWord = new Array(length).fill("_");
            hiddenWord[0] = word.charAt(0);
            hiddenWord[length - 1] = word.charAt(length - 1);
            hiddenWord.forEach(char => {
                wordArray.push(char);
            }, this);

            hiddenWords.push(hiddenWord.join(" "));
        }

        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
        description = this.game.add.text(game.world.centerX, constants.descriptionCoordinate, selectedWord.description, { fontSize: constants.smallText });
        description.anchor.x = 0.5;
    },

    addButton: function (text) {
        button = this.game.add.button(game.world.centerX, constants.newGameButtonCoordinate, constants.buttonImageName, this.newGame);
        button.scale.setTo(0.5, 1);
        button.anchor.x = 0.5;
        buttonText = this.game.add.text(game.world.centerX, constants.newGameButtonCoordinate + constants.buttonTextModifier, text);
        buttonText.anchor.x = 0.5;
        this.game.input.keyboard.enabled = false;
    },

    newGame: function () {
        wordArray = [];
        localStorage.setItem(constants.localStorageStatsName, JSON.stringify(stats));
        this.game.state.start(constants.menuStateName);
    },

    destroyGuessButton: function () {
        guessButton.destroy();
        guessButtonText.destroy();
    },

    revealWord: function () {
        var wordLength = wordToSearch.length;
        for (var i = 0; i < wordLength; i++) {
            wordArray[i] = wordToSearch.charAt(i);
        }
        this.updateWord();
    },

    updateWord: function() {
        displayedWord.destroy();
        displayedWord = this.game.add.text(game.world.centerX, constants.displayedWordCoordinate, wordArray.join(" "));
        displayedWord.anchor.x = 0.5;
    },

    checkMatch: function (letter) {
        if (triedLetters.indexOf(letter) >= 0) {
            message.destroy();
            message = this.game.add.text(game.world.centerX, constants.messageCoordinates, constants.triedLetterMessage, { fontSize: constants.smallText });
            message.anchor.x = 0.5;
            this.game.time.events.add(constants.messageTimerTime, function () {
                message.destroy();
            });
        } else {
            triedLetters += letter;

            if (wordToSearch.indexOf(letter) >= 0) {
                var index = wordToSearch.indexOf(letter);
                while (index >= 0) {
                    wordArray[index] = wordToSearch.charAt(index);
                    index = wordToSearch.indexOf(letter, index + 1);
                }

                stats.guessedLetters++;
                lettersStat.destroy();
                lettersStat = this.game.add.text(0, constants.guessedLettersCoordinate, constants.guessedLettersText + stats.guessedLetters, { fontSize: constants.smallText });

                this.updateWord();

                if (wordArray.indexOf("_") < 0) {
                    stats.playedGames++;
                    stats.wonGames++;
                    game.state.states.GameState.destroyGuessButton();

                    var win = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youWinText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    win.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }

            } else {
                errors++;
                wrongLetters += letter;
                guessedLetters.destroy();
                guessedLetters = this.game.add.text(0, constants.wrongLettersCoordintates, constants.wrongLettersText + wrongLetters, { fontSize: constants.smallText });
                this.hangingMan.destroy();
                this.hangingMan = this.game.add.sprite(game.world.centerX, 0, "hangingMan" + errors);
                this.hangingMan.anchor.x = 0.5;

                if (errors == constants.maxErrors) {
                    stats.playedGames++;
                    stats.lostGames++;
                    game.state.states.GameState.destroyGuessButton();

                    var lose = this.game.add.text(game.world.centerX, constants.resultTextCoordinate, constants.youLoseText, {
                        fontSize: constants.bigText, backgroundColor: constants.whiteColor
                    });
                    lose.anchor.x = 0.5;
                    this.addButton(constants.newGameText);
                }
            }
        }
    }
};<|endoftext|>


<commit_before>(function() {
  var onDeviceReady;

  document.addEventListener('deviceready', onDeviceReady, false);

  onDeviceReady = function() {
    return alert('device ready');
  };

}).call(this);
<commit_msg>update<commit_after>(function() {
  document.addEventListener('deviceready', (function() {
    return console.log('device ready');
  }), false);

}).call(this);
<|endoftext|>


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

  var controls = document.querySelector('#controls');
  controls.showDisplay = function() {
    chrome.app.window.create('build/display.html',
      {
        id: 'displayWindow',
        alwaysOnTop: true,
        frame: 'none',
        focused: false,
        hidden: true,
        resizable: false,
        state: 'maximized',
        visibleOnAllWorkspaces: true
      },
      function(displayWindow) {
        displayWindow.contentWindow.addEventListener('load', function(){
          displayWindow.outerBounds.left = 1930;
          displayWindow.maximize();
          displayWindow.show(false);
        });
    });
  };
})();
<commit_msg>Move display window to external display based on external display info.<commit_after>(function(){
  'use strict';

  var controller = {

    DISPLAY_WINDOW_ID: 'displayWindow',

    showDisplay: function() {
      if (chrome.app.window.get(this.DISPLAY_WINDOW_ID)) {
        return;
      }

      var externalDisplayInfo, queueMoveToExternalDisplay = false;
      chrome.system.display.getInfo(function(displayInfos) {
        for (var i = displayInfos.length - 1; i >= 0; i--) {
          if (!displayInfos[i].isPrimary && displayInfos[i].isEnabled) {
            externalDisplayInfo = displayInfos[i];
            break;
          }
        }
      });

      chrome.app.window.create('build/display.html',
        {
          id: this.DISPLAY_WINDOW_ID,
          alwaysOnTop: true,
          frame: 'none',
          focused: false,
          hidden: true,
          resizable: false,
          state: 'maximized',
          visibleOnAllWorkspaces: true
        },
        (function(displayWindow) {
          if (externalDisplayInfo)  {
            this.moveToExternalDisplay(displayWindow, externalDisplayInfo);
          } else {
            queueMoveToExternalDisplay = true;
          }
      }).bind(this));

    },

    moveToExternalDisplay: function(displayWindow, externalDisplayInfo) {
      displayWindow.contentWindow.addEventListener('load', function(){
        displayWindow.outerBounds.left = externalDisplayInfo.bounds.left;
        displayWindow.maximize();
        displayWindow.show(false);
      });
    }
  };

  var controls = document.querySelector('#controls');
  controls.showDisplay = controller.showDisplay.bind(controller);
})();
<|endoftext|>


<commit_before>const BASE_REQUEST_URL = 'https://maps.googleapis.com/maps/api/place/' +
                         'nearbysearch/json?' +
	                 'key=***REMOVED***&';
$(document).ready(function() {
  getCafes();

});

function getCafes(){
    var location = '-41.3064632,174.7749782';
	$.get(BASE_REQUEST_URL + 'location=' + location
                              + '&radius=5000&type=cafe', function (data) {
	    //var totallyLegitTableTM = $('table'); //TOCMMENT
		//var outerDiv = document.getElementByID("results");
        data.results.forEach(function(item) {
            var name = item.name;
            var lat = item.geometry.location.lat;
            var long = item.geometry.location.lng;

            var locationsNearBy = new Set();
            locationsNearBy.add(name);
            $.get(BASE_REQUEST_URL + 'location='+ lat + ',' + long + '&radius=100', function(surroundingPlaces){
              //var tableRow = document.createElement('tr');
			  var innerDiv = document.createElement('div');
			  //dont need atm //iDiv.id = 'innerDiv';
			  innerDiv.className = 'innerDiv';
              // $(tableRow).append($('td').text(name));
              //tableRow.insertCell(-1).appendChild(document.createTextNode(name));

			  innerDiv.innerHTML = name;
			  var resultDiv = document.createElement('div');
			  innerDiv.className = 'resultDiv';
              var listNearby = document.createElement('ul');

              //var right = tableRow.insertCell(-1).appendChild(listNearby);
			  resultDiv.append(listNearby);

              surroundingPlaces.results.forEach(function (it){
                if(!locationsNearBy.has(it.name)){
                  var point = document.createElement('li');
                  point.innerHTML=it.name;
                  listNearby.appendChild(point);
                  locationsNearBy.add(it.name);
                }
                // listNearby.appendChild(document.createElement('li').appendChild(document.createTextNode(it.name)))
              })
			  innerDiv.append(resultDiv);
              $('#results').append(innerDiv);
                // if(surroundingPlaces.results !== undefined) {
                //     surroundingPlaces.results.forEach(function (i2) {
                //         rightHandTable.append('
' + i2.name + '
');
                //     });
                // }
                // totallyLegitTableTM.append($('tr')
                //     .append($('td').append(item.name))
                //     .append($('td').append(rightHandTable)
                //     )
                // );
                // $('#results').append(totallyLegitTableTM);
                // alert('look!');
            });

        });
    });

}

function error(msg){
    console.log(msg);
}
<commit_msg>Working now<commit_after>const BASE_REQUEST_URL = 'https://maps.googleapis.com/maps/api/place/' +
                         'nearbysearch/json?' +
	                 'key=***REMOVED***&';
$(document).ready(function() {
  getCafes();

});

function getCafes(){
    var location = '-41.3064632,174.7749782';
	$.get(BASE_REQUEST_URL + 'location=' + location
                              + '&radius=5000&type=cafe', function (data) {
	    //var totallyLegitTableTM = $('table'); //TOCMMENT
		//var outerDiv = document.getElementByID("results");
        data.results.forEach(function(item) {
            var name = item.name;
            var lat = item.geometry.location.lat;
            var long = item.geometry.location.lng;

            var locationsNearBy = new Set();
            locationsNearBy.add(name);
            $.get(BASE_REQUEST_URL + 'location='+ lat + ',' + long + '&radius=100', function(surroundingPlaces){
              //var tableRow = document.createElement('tr');
			  var innerDiv = document.createElement('div');
			  //dont need atm //iDiv.id = 'innerDiv';
			  innerDiv.className = 'innerDiv';
              // $(tableRow).append($('td').text(name));
              //tableRow.insertCell(-1).appendChild(document.createTextNode(name));

			  innerDiv.innerHTML = name;

			  var resultDiv = document.createElement('div');
			  resultDiv.className = 'resultDiv';
              var listNearby = document.createElement('ul');

              //var right = tableRow.insertCell(-1).appendChild(listNearby);
			  resultDiv.append(listNearby);

              surroundingPlaces.results.forEach(function (it){
                if(!locationsNearBy.has(it.name)){
                  var point = document.createElement('li');
                  point.innerHTML=it.name;
                  listNearby.appendChild(point);
                  locationsNearBy.add(it.name);
                }
                // listNearby.appendChild(document.createElement('li').appendChild(document.createTextNode(it.name)))
              })
			  innerDiv.append(resultDiv);
              $('#results').append(innerDiv);
                // if(surroundingPlaces.results !== undefined) {
                //     surroundingPlaces.results.forEach(function (i2) {
                //         rightHandTable.append('
' + i2.name + '
');
                //     });
                // }
                // totallyLegitTableTM.append($('tr')
                //     .append($('td').append(item.name))
                //     .append($('td').append(rightHandTable)
                //     )
                // );
                // $('#results').append(totallyLegitTableTM);
                // alert('look!');
            });

        });
    });

}

function error(msg){
    console.log(msg);
}
<|endoftext|>


<commit_before>// define object variables
var Portfolio,
	LoadComponents,
	Projects,
	MotionBG;

var mob;

Portfolio = {

	// determines if user is mobile
	// - used as determinant for firing other functions
	"isMobile" : function() {
		if (/Mobi/.test(navigator.userAgent)) {
			//console.log("isMobile set to true");
			return true;
		} else {
			//console.log("isMobile remains false");
			return false;
		}
	},

	// hides all elements so they can fade in
	// (not hidden by default in case user has JS disabled)
	// - also provides additional DOM modification if user is mobile
	// - accepts arg 'bool', whether or not user is mobile
	"configure" : function(bool) {
		var // initialize selectors
		header = $("header"),
		name = $("#me"),
		ptOne = $("#pt1"),
		ptTwo = $("#pt2"),
		ptThree = $("#pt3"),
		pageNav = $(".page-nav"),
		sociNav = $(".social-nav"),
		projs = $(".project"),
		pic = $("#profile-pic");

		var hideElems = [projs];

		for (i = 0; i < hideElems.length; i++) {
			hideElems[i].css("opacity", 0);
		}

		// if (bool) {
		// 	pic.css("display", "none");
		// }

	},

	// listens for window location and project locations
	// anytime the user scrolls, will reveal project
	// if within parameters
	"projReveal" : function() {
		var // initialize selectors
		viewField = $(window),
		listenField = $("#project-container"),
		projectField = $(".project"),
		objBottom, winBottom;

		viewField.scroll(function(event) {
			listenField.find(projectField).each(function(i){
				objBottom = $(this).offset().top + $(this).outerHeight();
				winBottom = viewField.scrollTop() + viewField.height();
				if(winBottom > objBottom) {
					$(this).addClass("fadeIn animate-norm");
				}
			});
		});

	},

	// animation sequence for when the page loads
	"loadSequence" : function() {
		var // initialize selectors
		header = $("header"),
		name = $("#me"),
		ptOne = $("#pt1"),
		ptTwo = $("#pt2"),
		ptThree = $("#pt3"),
		pageNav = $(".page-nav"),
		sociNav = $(".social-nav");

		// hide name and header
		setTimeout(function() {
			LoadComponents.init(header, name);
		}, 1000); //500

		// reveal caption pt 1
		setTimeout(function() {
			LoadComponents.inCenterSlow(ptOne)
		}, 2500); //1000

		// reveal caption pt 2
		setTimeout(function() {
			LoadComponents.inCenterSlow(ptTwo)
		}, 3500);

/* 		// reveal caption pt 3
		setTimeout(function() {
			LoadComponents.mainThree(ptThree)
		}, 2900); */

		// reveal header
		setTimeout(function() {
			LoadComponents.headBar(header)
		}, 5000); //3800

		// reveal navigation components
		setTimeout(function() {
			LoadComponents.headContent(pageNav, sociNav)
		}, 5500); // 4300

	}
}

// Contains vague funtions associated with the load sequence.
// More in depth functions are in the Portfolio object.
LoadComponents = {

	"init" : function(componentOne, componentTwo) {
		// componentOne.addClass("animate-slow fadeIn");
		componentTwo.addClass("animate-slow fadeIn");
	},

	"inLeft" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-norm slideInLeftDramatic");
	},

	"inCenter" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-norm fadeIn");
	},

	"inCenterSlow" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-slow fadeIn");
	},

	"inRight" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-norm slideInRightDramatic");
	},

	"headBar" : function(component) {
		component.addClass("animate-norm fadeIn");
	},

	"headContent" : function(componentOne, componentTwo) {
		componentOne.css("opacity", 1);
		componentOne.addClass("animate-norm slideInLeft");
		componentTwo.css("opacity", 1);
		componentTwo.addClass("animate-norm slideInDown");
	}

}

MotionBG = {
	"init" : function() {

		// define canvas
		var canvas = document.createElement('canvas'),
			context = canvas.getContext('2d');

		var bg = document.getElementsByClassName('background');
		bg = bg[0];

		w = canvas.width = window.innerWidth;
		h = canvas.height = window.innerHeight;

		bg.appendChild(canvas);

		// particle parameters
		pCount = 0;
		var particles = {},
			pIndex = 0,
			settings = {
				density: 20,
				pSize: 2,
				gravity: 0,
				floor: canvas.height,
				leftWall: canvas.width * 0.1,
				rightWall: canvas.width
			}

		// particle origin and velocity
		function Particle() {
			this.x = Math.random() * w;
			this.y = Math.random() * h;

			switch (Math.floor(Math.random() * 4)) {
			case 0:
				this.vx = .025;
				this.vy = .025;
				break;
			case 1:
				this.vx = -.025;
				this.vy = -.025;
				break;
			case 2:
				this.vx = -.025;
				this.vy = .025;
				break;
			case 3:
				this.vx = .025;
				this.vy = -.025;
				break;
			}

			pIndex ++;
			particles[pIndex] = this;
			//this.id = pIndex;
			//this.life = 0;
			//this.maxLife = 500;
		}

		// motion and particle size & color
		Particle.prototype.draw = function() {
			this.x += this.vx;
			this.y += this.vy;

			//this.life++;
			//if (this.life >= this.maxLife) {
			//  delete particles[this.id];
			//}
			context.beginPath();
			context.fillStyle = "#b30000";
			context.arc(this.x, this.y, settings.pSize, 0, Math.PI*2, true);
			context.closePath();
			context.fill();
			//context.clearRect(settings.leftWall, settings.groundLevel, w, h);
			//context.fillStyle = '#b30000';
			//context.fillRect(this.x, this.y, 5, 5);

		}

		function float() {
			// var grd = context.createRadialGradient(w/2, h/2, 0, w/2, h/2, w);
			// grd.addColorStop(0, '#f2f2f2');
			// grd.addColorStop(1, '#333');
			// context.fillStyle = grd;
			// context.fillRect(0, 0, w, h);

			for (var i in particles) {
			particles[i].draw();
			}
		}

		// canvas background and particle spawn
		var spawn = setInterval(function() {
			// var grd = context.createRadialGradient(w/2, h/2, 0, w/2, h/2, w);
			// grd.addColorStop(0, '#f2f2f2');
			// grd.addColorStop(1, '#333');
			// context.fillStyle = grd;
			// context.fillRect(0, 0, w, h);
			if (pCount >= 500) {
			clearInterval(spawn);
			setInterval(float, 10);
			}
			for (var i = 0; i < settings.density; i++) {
			if (Math.random() > .8) {
				new Particle();
				pCount += 1;
			}

			}
			for (var i in particles) {
			particles[i].draw();
			}
		}, 10);

	}
}

// Hides animated elems,
// plays load sequence,
// enables scroll listening
window.onload = function() {
	// simulate loading delay
	mob = Portfolio.isMobile();
	Portfolio.configure(mob);
	// MotionBG.init();
	// Portfolio.loadSequence();
	Portfolio.projReveal();
}
hljs.initHighlightingOnLoad();<commit_msg>Particle effect<commit_after>// define object variables
var Portfolio,
	LoadComponents,
	Projects,
	MotionBG;

var mob;

Portfolio = {

	// determines if user is mobile
	// - used as determinant for firing other functions
	"isMobile" : function() {
		if (/Mobi/.test(navigator.userAgent)) {
			//console.log("isMobile set to true");
			return true;
		} else {
			//console.log("isMobile remains false");
			return false;
		}
	},

	// hides all elements so they can fade in
	// (not hidden by default in case user has JS disabled)
	// - also provides additional DOM modification if user is mobile
	// - accepts arg 'bool', whether or not user is mobile
	"configure" : function(bool) {
		var // initialize selectors
		header = $("header"),
		name = $("#me"),
		ptOne = $("#pt1"),
		ptTwo = $("#pt2"),
		ptThree = $("#pt3"),
		pageNav = $(".page-nav"),
		sociNav = $(".social-nav"),
		projs = $(".project"),
		pic = $("#profile-pic");

		var hideElems = [projs];

		for (i = 0; i < hideElems.length; i++) {
			hideElems[i].css("opacity", 0);
		}

		// if (bool) {
		// 	pic.css("display", "none");
		// }

	},

	// listens for window location and project locations
	// anytime the user scrolls, will reveal project
	// if within parameters
	"projReveal" : function() {
		var // initialize selectors
		viewField = $(window),
		listenField = $("#project-container"),
		projectField = $(".project"),
		objBottom, winBottom;

		viewField.scroll(function(event) {
			listenField.find(projectField).each(function(i){
				objBottom = $(this).offset().top + $(this).outerHeight();
				winBottom = viewField.scrollTop() + viewField.height();
				if(winBottom > objBottom) {
					$(this).addClass("fadeIn animate-norm");
				}
			});
		});

	},

	// animation sequence for when the page loads
	"loadSequence" : function() {
		var // initialize selectors
		header = $("header"),
		name = $("#me"),
		ptOne = $("#pt1"),
		ptTwo = $("#pt2"),
		ptThree = $("#pt3"),
		pageNav = $(".page-nav"),
		sociNav = $(".social-nav");

		// hide name and header
		setTimeout(function() {
			LoadComponents.init(header, name);
		}, 1000); //500

		// reveal caption pt 1
		setTimeout(function() {
			LoadComponents.inCenterSlow(ptOne)
		}, 2500); //1000

		// reveal caption pt 2
		setTimeout(function() {
			LoadComponents.inCenterSlow(ptTwo)
		}, 3500);

/* 		// reveal caption pt 3
		setTimeout(function() {
			LoadComponents.mainThree(ptThree)
		}, 2900); */

		// reveal header
		setTimeout(function() {
			LoadComponents.headBar(header)
		}, 5000); //3800

		// reveal navigation components
		setTimeout(function() {
			LoadComponents.headContent(pageNav, sociNav)
		}, 5500); // 4300

	}
}

// Contains vague funtions associated with the load sequence.
// More in depth functions are in the Portfolio object.
LoadComponents = {

	"init" : function(componentOne, componentTwo) {
		// componentOne.addClass("animate-slow fadeIn");
		componentTwo.addClass("animate-slow fadeIn");
	},

	"inLeft" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-norm slideInLeftDramatic");
	},

	"inCenter" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-norm fadeIn");
	},

	"inCenterSlow" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-slow fadeIn");
	},

	"inRight" : function(component) {
		component.css("opacity", 1);
		component.addClass("animate-norm slideInRightDramatic");
	},

	"headBar" : function(component) {
		component.addClass("animate-norm fadeIn");
	},

	"headContent" : function(componentOne, componentTwo) {
		componentOne.css("opacity", 1);
		componentOne.addClass("animate-norm slideInLeft");
		componentTwo.css("opacity", 1);
		componentTwo.addClass("animate-norm slideInDown");
	}

}

MotionBG = {
	"init" : function() {

		// define canvas
		var canvas = document.createElement('canvas'),
			context = canvas.getContext('2d');

		var bg = document.getElementsByClassName('background');
		bg = bg[0];

		w = canvas.width = window.innerWidth;
		h = canvas.height = window.innerHeight;

		bg.appendChild(canvas);

		// particle parameters
		pCount = 0;
		var particles = {},
			pIndex = 0,
			settings = {
				density: 20,
				pSize: 1,
				gravity: 0,
				floor: canvas.height,
				leftWall: canvas.width * 0.1,
				rightWall: canvas.width
			}

		// particle origin and velocity
		function Particle() {
			this.x = Math.random() * w;
			this.y = Math.random() * h;

			switch (Math.floor(Math.random() * 4)) {
			case 0:
				this.vx = .025;
				this.vy = .025;
				break;
			case 1:
				this.vx = -.025;
				this.vy = -.025;
				break;
			case 2:
				this.vx = -.025;
				this.vy = .025;
				break;
			case 3:
				this.vx = .025;
				this.vy = -.025;
				break;
			}

			pIndex ++;
			particles[pIndex] = this;
			//this.id = pIndex;
			//this.life = 0;
			//this.maxLife = 500;
		}

		// motion and particle size & color
		Particle.prototype.draw = function() {
			this.x += this.vx;
			this.y += this.vy;

			//this.life++;
			//if (this.life >= this.maxLife) {
			//  delete particles[this.id];
			//}
			context.beginPath();
			// context.fillStyle = '#bdbdbd';
			context.fillStyle = '#4d4d4f';
			context.arc(this.x, this.y, settings.pSize, 0, Math.PI*2, true);
			context.closePath();
			context.fill();
			// context.clearRect(settings.leftWall, settings.groundLevel, w, h);
			// context.fillStyle = '#bdbdbd';
			// context.fillRect(this.x, this.y, 10, 1);

		}

		function float() {
			// var grd = context.createRadialGradient(w/2, h/2, 0, w/2, h/2, w);
			// grd.addColorStop(0, '#000000');
			// grd.addColorStop(1, '#6CABFF');
			// context.fillStyle = grd;
			// context.fillRect(0, 0, w, h);

			for (var i in particles) {
			particles[i].draw();
			}
		}

		// canvas background and particle spawn
		var spawn = setInterval(function() {
			var grd = context.createRadialGradient(w/2, h/2, 0, w/2, h/2, w);
			grd.addColorStop(0, '#000000');
			grd.addColorStop(1, '#6CABFF');
			context.fillStyle = grd;
			context.fillRect(0, 0, w, h);
			if (pCount >= 500) {
			clearInterval(spawn);
			setInterval(float, 10);
			}
			for (var i = 0; i < settings.density; i++) {
			if (Math.random() > .8) {
				new Particle();
				pCount += 1;
			}

			}
			for (var i in particles) {
			particles[i].draw();
			}
		}, 10);

	}
}

// Hides animated elems,
// plays load sequence,
// enables scroll listening
window.onload = function() {
	// simulate loading delay
	mob = Portfolio.isMobile();
	Portfolio.configure(mob);
	MotionBG.init();
	// Portfolio.loadSequence();
	Portfolio.projReveal();
}
hljs.initHighlightingOnLoad();<|endoftext|>


<commit_before>var jp = jp || {};

$(document).ready(function () {
    var $BTN_PATH = $('#calculate'),
        $BTN_ERASE = $('#erase');

    var _event = {
        findPath: function () {
            var timeEnd,
                timeStart,
                begin = jp.visual.getBegin(),
                end = jp.visual.getEnd(),
                maxSteps = parseInt($('#input-max-steps').val(), 10);

            jp.pathFinder.playerSize = jp.visual.getPlayerSize();
            jp.map.setData(jp.visual.getCollisionMap());
            timeStart = Date.now();

            // @TODO If the player is up in the air we are in the middle of a jump, do not find a path during a jump (error prone)
            var path = jp.pathFinder.findPath(begin.x, begin.y, end.x, end.y, maxSteps);

            timeEnd = Date.now();
            jp.pathFinder.setVisual();
            jp.visual.setTileGroup(path, 'path');

            $('#time').html((timeEnd - timeStart) / 1000);
            $('#calls').html(jp.pathFinder.calls);
        }
    };

    var main = {
        init: function () {
            jp.visual.init();
            this.bind();
        },

        bind: function () {
            $BTN_PATH.click(_event.findPath);
            $BTN_ERASE.click(jp.visual.erase);
        }
    };

    main.init();
});<commit_msg>Fixed broken clearance values<commit_after>var jp = jp || {};

$(document).ready(function () {
    var $BTN_PATH = $('#calculate'),
        $BTN_ERASE = $('#erase');

    var _event = {
        findPath: function () {
            var timeEnd,
                timeStart,
                begin = jp.visual.getBegin(),
                end = jp.visual.getEnd(),
                maxSteps = parseInt($('#input-max-steps').val(), 10);

            jp.pathFinder.playerSize = jp.visual.getPlayerSize();
            jp.map.setData(jp.visual.getCollisionMap());
            timeStart = Date.now();

            // @TODO If the player is up in the air we are in the middle of a jump, do not find a path during a jump (error prone)
            var path = jp.pathFinder.findPath(begin.x + jp.pathFinder.playerSize - 1, begin.y + jp.pathFinder.playerSize - 1, end.x, end.y, maxSteps);

            timeEnd = Date.now();
            jp.pathFinder.setVisual();
            jp.visual.setTileGroup(path, 'path');

            $('#time').html((timeEnd - timeStart) / 1000);
            $('#calls').html(jp.pathFinder.calls);
        }
    };

    var main = {
        init: function () {
            jp.visual.init();
            this.bind();
        },

        bind: function () {
            $BTN_PATH.click(_event.findPath);
            $BTN_ERASE.click(jp.visual.erase);
        }
    };

    main.init();
});<|endoftext|>


<commit_before>
    /* ------------------------ MAIN ------------------- */
    $('.overlay').hide();

    var menu = function() {
        ui_location = 'menu';

        $('#external-hud').hide();

        // show menu overlay
        $('#main-menu').show();
    };

    var pause = function() {
        // stop the main interval
        if (ui_location == 'game') cancelAnimationFrame(mainAnimation);
        if (ui_location == 'editor') cancelAnimationFrame(editorAnimation);

        // show pause menu
        if (ui_location == 'game') $('#pause-menu').show();
        else if (ui_location == 'editor') $('#editor-menu').show();

        UTIL.pauseMusic(backgroundMusic);
    };

    // NEW GAME
    var reset = function() {
        alert('done');
    };

    // UPDATE SCENE
    var update = function(modifier) {

        /* turn tank body to direction */
        if (37 in keysDown) { // left arrow pressed
            player.turnBody(modifier, 'ccw');
        }

        if (39 in keysDown) { // right arrow pressed
            player.turnBody(modifier, 'cw');
        }

        if (!(37 in keysDown) && !(39 in keysDown)) { // no left/right arrows pressed
            player.turnBody(modifier, 'hold');
        }

        if (38 in keysDown) { // up arrow pressed
            player.move(modifier, 'forward');
        }
        else {
            player.move(modifier, 'forward-stop');
        }

        if (40 in keysDown) { // down arrow pressed
            player.move(modifier, 'reverse');
        }
        else {
            player.move(modifier, 'reverse-stop');
        }

        if (mouseDownLeft) {
            player.fire();
        }

        if (mouseDownRight) {
            var msg = {};

            msg.cmd = 'get_waypoint_random';
            msg.data = {};
            msg.data.start = [0, 0];
            msg.data.angle = 45; // body angle

            LOAD.worker.sendMessage(1, msg);
        }

        /* turn turret (based on current facing angle) */
        player.turnTurret(modifier, mousePos.mX, mousePos.mY);

        // enemy AI here, but random movements for now
        // calculate distance between player and enemy
        var d = Math.sqrt(Math.pow(player.config.oX-enemy.config.oX, 2) + Math.pow(player.config.oY-enemy.config.oY, 2));
        if (d < 200) {
            enemy.move(modifier, 'forward');
        }
        else if (d > 400) {
            enemy.move(modifier, 'reverse');
        }
        enemy.turnTurret(modifier, player.config.oX, player.config.oY);
        enemy2.turnTurret(modifier, player.config.oX, player.config.oY);
        var rng = Math.floor(Math.random() * 250) + 1;
        if (rng == 1 || rng == 4 || rng == 7) {
            enemy.fire();
        }
        if (rng == 50 || rng == 18 || rng == 101) {
            enemy2.fire();
        }
        // point enemy turret to player and fire

        // Update all projectiles.
        for (var i = 0; i < projectiles.length; i++) {
            if (projectiles[i].config.active) {
                projectiles[i].update(modifier);
            }
        }
    };

    // Editor UPDATE
    var editorUpdate = function() {

        if (cs_asset_select_ok) {

            if (96 in keysDown) { // num 0
                MAP.nextPlaceable();
            }

            if (17 in keysDown) { // ctrl
                MAP.toggleMode();
            }

            cs_asset_select_ok = false;

            clearTimeout(csas_timeout);

            csas_timeout = setTimeout(function() { cs_asset_select_ok = true }, 75);
        }

        if (cs_movement_ok) {

            if (37 in keysDown) { // left arrow
                MAP.moveCursor('L');
            }

            if (39 in keysDown) { // right arrow
                MAP.moveCursor('R');
            }

            if (38 in keysDown) { // up arrow
                MAP.moveCursor('U');
            }

            if (40 in keysDown) { // down arrow
                MAP.moveCursor('D');
            }

            cs_movement_ok = false;

            clearTimeout(csmv_timeout);

            csmv_timeout = setTimeout(function() { cs_movement_ok = true }, 50);
        }

        if (cs_placement_ok) {

            if (13 in keysDown || mouseDownLeft) { // enter
                MAP.placeObject();
            }

            cs_placement_ok = false;

            clearTimeout(cspo_timeout);

            cspo_timeout = setTimeout(function() { cs_placement_ok = true; }, 100);
        }

        if (110 in keysDown || mouseDownRight ) {
            MAP.removeObject();
        }

    }

    // DRAW SCENE
    var renderCanvas = function() {

        CANVAS.clear(ctx);

        CANVAS.drawDestructibles(ctx);
        CANVAS.drawPowerUps(ctx);
        CANVAS.drawTanks(ctx);
        CANVAS.drawProjectiles(ctx);

    };

    var renderExtern = function() {
        // draw player health
        var healthFraction = player.config.health / player.config.maxHealth;
        var cHealth = player.config.health <= 0 ? 0 : 1024 * healthFraction; // 420
        var remBar = hp.style.width;
        remBar = remBar.replace('px', '');

        // change health bar color as health drops
        if      (healthFraction >= 0.75) hp.style.backgroundColor = '#66CD00'; // green        @ >= 75%
        else if (healthFraction >= 0.50) hp.style.backgroundColor = '#FFFF00'; // yellow       @ >= 50%
        else if (healthFraction >= 0.25) hp.style.backgroundColor = '#FE4902'; // vermillion   @ >= 25%
        else                             hp.style.backgroundColor = '#FF0000'; // red          @ < 25%

        hp.style.width = cHealth + 'px';

        var diff = remBar - cHealth;
        hNum.innerHTML = player.config.health.toFixed(2);

        if (diff > 0) {
            // if health is reduced, animate
            $('#current-health-anim').stop();
            $('#current-health-anim').animate({width: cHealth}, 500);
        }
        else if (diff < 0) {
            // if health is restored, don't animate
            $('#current-health-anim').stop();
            $('#current-health-anim').width(cHealth);
        }
    }

    // MAIN
    var main = function() {
        var now = performance.now();
        var delta = now - then;

        update(delta / 1000);
        renderCanvas(); // render canvas objects
        renderExtern(); // render external objects

        then = now;
        mainAnimation = requestAnimationFrame(main);
    };

    // Faux Main (Map Editor)
    var editor = function() {
        editorUpdate();
        renderCanvas();

        CANVAS.drawStartingPoints(ctx);
        MAP.drawPlaceableGhost(ctx);

        editorAnimation = requestAnimationFrame(editor);
    }

    // START
    var start = function(player_name) {
        ui_location = 'game';

        $('#external-hud').show();

        LOAD.gameSettings(player_name);
        LOAD.worker.pathFinder(current_map, 1); // worker test, random id
        attachGameEventListeners();
        then = performance.now();
        UTIL.playMusic(backgroundMusic);

        main();
    };

    // Editor START
    var startMapEditor = function() {

        ui_location = 'editor';

        // clear the arrays
        powerups.clear();
        tanks.clear();
        projectiles.clear();
        destructibles.clear();
        startingpoints.clear();

        attachGameEventListeners();
        attachEditorEventListeners();

        editor();
    }

    menu();
    attachMenuEventListeners();
    //start();<commit_msg>the projectiles array will now be cleaned after each frame<commit_after>
    /* ------------------------ MAIN ------------------- */
    $('.overlay').hide();

    var menu = function() {
        ui_location = 'menu';

        $('#external-hud').hide();

        // show menu overlay
        $('#main-menu').show();
    };

    var pause = function() {
        // stop the main interval
        if (ui_location == 'game') cancelAnimationFrame(mainAnimation);
        if (ui_location == 'editor') cancelAnimationFrame(editorAnimation);

        // show pause menu
        if (ui_location == 'game') $('#pause-menu').show();
        else if (ui_location == 'editor') $('#editor-menu').show();

        UTIL.pauseMusic(backgroundMusic);
    };

    // NEW GAME
    var reset = function() {
        alert('done');
    };

    // UPDATE SCENE
    var update = function(modifier) {

        /* turn tank body to direction */
        if (37 in keysDown) { // left arrow pressed
            player.turnBody(modifier, 'ccw');
        }

        if (39 in keysDown) { // right arrow pressed
            player.turnBody(modifier, 'cw');
        }

        if (!(37 in keysDown) && !(39 in keysDown)) { // no left/right arrows pressed
            player.turnBody(modifier, 'hold');
        }

        if (38 in keysDown) { // up arrow pressed
            player.move(modifier, 'forward');
        }
        else {
            player.move(modifier, 'forward-stop');
        }

        if (40 in keysDown) { // down arrow pressed
            player.move(modifier, 'reverse');
        }
        else {
            player.move(modifier, 'reverse-stop');
        }

        if (mouseDownLeft) {
            player.fire();
        }

        if (mouseDownRight) {
            var msg = {};

            msg.cmd = 'get_waypoint_random';
            msg.data = {};
            msg.data.start = [0, 0];
            msg.data.angle = 45; // body angle

            LOAD.worker.sendMessage(1, msg);
        }

        /* turn turret (based on current facing angle) */
        player.turnTurret(modifier, mousePos.mX, mousePos.mY);

        // enemy AI here, but random movements for now
        // calculate distance between player and enemy
        var d = Math.sqrt(Math.pow(player.config.oX-enemy.config.oX, 2) + Math.pow(player.config.oY-enemy.config.oY, 2));
        if (d < 200) {
            enemy.move(modifier, 'forward');
        }
        else if (d > 400) {
            enemy.move(modifier, 'reverse');
        }
        enemy.turnTurret(modifier, player.config.oX, player.config.oY);
        enemy2.turnTurret(modifier, player.config.oX, player.config.oY);
        var rng = Math.floor(Math.random() * 250) + 1;
        if (rng == 1 || rng == 4 || rng == 7) {
            enemy.fire();
        }
        if (rng == 50 || rng == 18 || rng == 101) {
            enemy2.fire();
        }
        // point enemy turret to player and fire

        // Update all projectiles.
        for (var i = 0; i < projectiles.length; i++) {
            if (projectiles[i].config.active) {
                projectiles[i].update(modifier);
            }
        }

        // Remove all inactive projectiles. This keeps the projectile array from accumulating inactive objects.
        projectiles = projectiles.filter(function (item) {
            return item.config.active;
        });
    };

    // Editor UPDATE
    var editorUpdate = function() {

        if (cs_asset_select_ok) {

            if (96 in keysDown) { // num 0
                MAP.nextPlaceable();
            }

            if (17 in keysDown) { // ctrl
                MAP.toggleMode();
            }

            cs_asset_select_ok = false;

            clearTimeout(csas_timeout);

            csas_timeout = setTimeout(function() { cs_asset_select_ok = true }, 75);
        }

        if (cs_movement_ok) {

            if (37 in keysDown) { // left arrow
                MAP.moveCursor('L');
            }

            if (39 in keysDown) { // right arrow
                MAP.moveCursor('R');
            }

            if (38 in keysDown) { // up arrow
                MAP.moveCursor('U');
            }

            if (40 in keysDown) { // down arrow
                MAP.moveCursor('D');
            }

            cs_movement_ok = false;

            clearTimeout(csmv_timeout);

            csmv_timeout = setTimeout(function() { cs_movement_ok = true }, 50);
        }

        if (cs_placement_ok) {

            if (13 in keysDown || mouseDownLeft) { // enter
                MAP.placeObject();
            }

            cs_placement_ok = false;

            clearTimeout(cspo_timeout);

            cspo_timeout = setTimeout(function() { cs_placement_ok = true; }, 100);
        }

        if (110 in keysDown || mouseDownRight ) {
            MAP.removeObject();
        }

    }

    // DRAW SCENE
    var renderCanvas = function() {

        CANVAS.clear(ctx);

        CANVAS.drawDestructibles(ctx);
        CANVAS.drawPowerUps(ctx);
        CANVAS.drawTanks(ctx);
        CANVAS.drawProjectiles(ctx);

    };

    var renderExtern = function() {
        // draw player health
        var healthFraction = player.config.health / player.config.maxHealth;
        var cHealth = player.config.health <= 0 ? 0 : 1024 * healthFraction; // 420
        var remBar = hp.style.width;
        remBar = remBar.replace('px', '');

        // change health bar color as health drops
        if      (healthFraction >= 0.75) hp.style.backgroundColor = '#66CD00'; // green        @ >= 75%
        else if (healthFraction >= 0.50) hp.style.backgroundColor = '#FFFF00'; // yellow       @ >= 50%
        else if (healthFraction >= 0.25) hp.style.backgroundColor = '#FE4902'; // vermillion   @ >= 25%
        else                             hp.style.backgroundColor = '#FF0000'; // red          @ < 25%

        hp.style.width = cHealth + 'px';

        var diff = remBar - cHealth;
        hNum.innerHTML = player.config.health.toFixed(2);

        if (diff > 0) {
            // if health is reduced, animate
            $('#current-health-anim').stop();
            $('#current-health-anim').animate({width: cHealth}, 500);
        }
        else if (diff < 0) {
            // if health is restored, don't animate
            $('#current-health-anim').stop();
            $('#current-health-anim').width(cHealth);
        }
    }

    // MAIN
    var main = function() {
        var now = performance.now();
        var delta = now - then;

        update(delta / 1000);
        renderCanvas(); // render canvas objects
        renderExtern(); // render external objects

        then = now;
        mainAnimation = requestAnimationFrame(main);
    };

    // Faux Main (Map Editor)
    var editor = function() {
        editorUpdate();
        renderCanvas();

        CANVAS.drawStartingPoints(ctx);
        MAP.drawPlaceableGhost(ctx);

        editorAnimation = requestAnimationFrame(editor);
    }

    // START
    var start = function(player_name) {
        ui_location = 'game';

        $('#external-hud').show();

        LOAD.gameSettings(player_name);
        LOAD.worker.pathFinder(current_map, 1); // worker test, random id
        attachGameEventListeners();
        then = performance.now();
        UTIL.playMusic(backgroundMusic);

        main();
    };

    // Editor START
    var startMapEditor = function() {

        ui_location = 'editor';

        // clear the arrays
        powerups.clear();
        tanks.clear();
        projectiles.clear();
        destructibles.clear();
        startingpoints.clear();

        attachGameEventListeners();
        attachEditorEventListeners();

        editor();
    }

    menu();
    attachMenuEventListeners();
    //start();<|endoftext|>


<commit_before>// ;(function(){
//   "use strict";
// var playerTurn = {
//   turn: true,
//   sign: "tic",
//   player: {
//     one: {
//       name: "",
//       turn: true
//     },
//     two: {
//       name: "",
//       turn: false
//     }
//   }
// }
// var module = (function () {
//   var privateGameCounter, append;
//   append = function( foo ){
//     var foo = 0;
//     if(foo%2==0){
//       $("td").on("click", function( foo ){
//         if($(this).hasClass("empty")){
//           $(this).addClass("tic");
//           $(this).removeClass("empty");
//           foo++;
//           console.log("tic");
//           console.log(foo);
//           return foo;
//         }
//       });
//     } else {
//       if($(this).hasClass("empty")){
//         $(this).addClass("tac");
//         $(this).removeClass("empty");
//         foo++;
//         console.log("tac");
//         console.log(foo);
//         return foo;
//       }
//     }
//   }
//   return {
//     myPublicFunction: $("td").click(function(){
//       append( "bar" );
//     })
//   }
// })();

(function(){
  var tic, tac, count, counter, play, turn;
  turn = 0;
  tic = function(){
    // $("td").mousedown(function(){
      if($(this).hasClass("empty")){
        $(this).addClass("tic");
        $(this).removeClass("empty");
      }
    // })
  }
  tac = function(){
    // $("td").mousedown(function(){
      if($(this).hasClass("empty")){
        $(this).addClass("tac");
        $(this).removeClass("empty");
      }
    // })
  }
  counter = function (){
    turn+=1;
    console.log(turn);
    return turn;
  }
  play = function(){
    if(turn % 2 === 0){
      tic.call(this);
    } else if(turn % 2 === 1){
      tac.call(this);
    } else{
      return turn;
    }
  }

  $("td").click(function(){
    play.call(this);
    counter();
  });

})();

// (function append(){
//   $("td").click(function(){
//     if(playerTurn.turn === true && $(this).hasClass("empty")){
//       $(this).addClass("tic");
//       $(this).removeClass("selected");
//       gameTurn();
//       $(this).removeClass("empty");
//       winner();
//     } else if (playerTurn.turn === false && $(this).hasClass("empty")){
//       $(this).addClass("tac");
//       $(this).removeClass("selected");
//       gameTurn();
//       $(this).removeClass("empty");
//       winner();
//     }
//   })
// }());
<commit_msg>Counter Working!<commit_after>// ;(function(){
//   "use strict";
// var playerTurn = {
//   turn: true,
//   sign: "tic",
//   player: {
//     one: {
//       name: "",
//       turn: true
//     },
//     two: {
//       name: "",
//       turn: false
//     }
//   }
// }
// var module = (function () {
//   var privateGameCounter, append;
//   append = function( foo ){
//     var foo = 0;
//     if(foo%2==0){
//       $("td").on("click", function( foo ){
//         if($(this).hasClass("empty")){
//           $(this).addClass("tic");
//           $(this).removeClass("empty");
//           foo++;
//           console.log("tic");
//           console.log(foo);
//           return foo;
//         }
//       });
//     } else {
//       if($(this).hasClass("empty")){
//         $(this).addClass("tac");
//         $(this).removeClass("empty");
//         foo++;
//         console.log("tac");
//         console.log(foo);
//         return foo;
//       }
//     }
//   }
//   return {
//     myPublicFunction: $("td").click(function(){
//       append( "bar" );
//     })
//   }
// })();

(function(){
  var tic, tac, count, counter, play, turn;
  turn = 0;
  tic = function(){
    // $("td").mousedown(function(){
    if($(this).hasClass("empty")){
      $(this).addClass("tic");
      $(this).removeClass("empty");
    }
    // })
  }
  tac = function(){
    // $("td").mousedown(function(){
    if($(this).hasClass("empty")){
      $(this).addClass("tac");
      $(this).removeClass("empty");
    }
    // })
  }
  counter = function (){
    if(!$(this).hasClass("empty") && !$(this).hasClass("played")){
      turn+=1;
      $(this).addClass("played");
      console.log(turn);
      return turn;
    } else {
      return turn;
    }
  }
  play = function(){
    if(turn % 2 === 0){
      tic.call(this);
    } else if(turn % 2 === 1){
      tac.call(this);
    } else{
      return turn;
    }
  }

  $("td").click(function(){
    play.call(this);
    counter.call(this);
  });

})();

// (function append(){
//   $("td").click(function(){
//     if(playerTurn.turn === true && $(this).hasClass("empty")){
//       $(this).addClass("tic");
//       $(this).removeClass("selected");
//       gameTurn();
//       $(this).removeClass("empty");
//       winner();
//     } else if (playerTurn.turn === false && $(this).hasClass("empty")){
//       $(this).addClass("tac");
//       $(this).removeClass("selected");
//       gameTurn();
//       $(this).removeClass("empty");
//       winner();
//     }
//   })
// }());
<|endoftext|>


<commit_before>//build the list of games
var games = [];
var game_list = $.ajax('http://soniccenter.org/source/utilities/codebot.php?choice=9&site=1')
var matches = mystring.match(/\S+?;/g);
for (var i in matches) {
	var match = game_list[i].match(/(\d+)-([^;]+)/);
	games.push({'id': match[1], 'name': match[2]})
}
<commit_msg>unneeded for now<commit_after><|endoftext|>


<commit_before>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */
(function() {
  'use strict';

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors. See
  // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
  var isLocalhost = Boolean(window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
    );

  if ('serviceWorker' in navigator &&
      (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      // updatefound is fired if service-worker.js changes.
      registration.onupdatefound = function() {
        // updatefound is also fired the very first time the SW is installed,
        // and there's no need to prompt for a reload at that point.
        // So check here to see if the page is already controlled,
        // i.e. whether there's an existing service worker.
        if (navigator.serviceWorker.controller) {
          // The updatefound event implies that registration.installing is set:
          // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
          var installingWorker = registration.installing;

          installingWorker.onstatechange = function() {
            switch (installingWorker.state) {
              case 'installed':
                // At this point, the old content will have been purged and the
                // fresh content will have been added to the cache.
                // It's the perfect time to display a "New content is
                // available; please refresh." message in the page's interface.
                break;

              case 'redundant':
                throw new Error('The installing ' +
                                'service worker became redundant.');

              default:
                // Ignore
            }
          };
        }
      };
    }).catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
  }

  // Your custom JavaScript goes here

   var myImage = document.querySelector('img');

   myImage.onclick = function() {
    var mySrc = myImage.getAttribute('src');
    if(mySrc === 'images/chargers2.jpg') {
      myImage.setAttribute ('src','images/chargers3.jpg');
    } else {
      myImage.setAttribute ('src','images/chargers2.jpg');
    }
   }

    var myButton = document.querySelector('button#change-user');
    var myHeading = document.querySelector('h1');
    debugger;

    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.textContent = 'Good day to you,' + myName;
    }

    if(!localStorage.getItem('name')) {
      setUserName();
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.textContent = 'Good day to you,' + storedName;
    }

    myButton.onclick = function() {
      setUserName();
    }
  });<commit_msg>Commit<commit_after>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */
(function() {
  'use strict';

  // Check to make sure service workers are supported in the current browser,
  // and that the current page is accessed from a secure origin. Using a
  // service worker from an insecure origin will trigger JS console errors. See
  // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features
  var isLocalhost = Boolean(window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
    );

  if ('serviceWorker' in navigator &&
      (window.location.protocol === 'https:' || isLocalhost)) {
    navigator.serviceWorker.register('service-worker.js')
    .then(function(registration) {
      // updatefound is fired if service-worker.js changes.
      registration.onupdatefound = function() {
        // updatefound is also fired the very first time the SW is installed,
        // and there's no need to prompt for a reload at that point.
        // So check here to see if the page is already controlled,
        // i.e. whether there's an existing service worker.
        if (navigator.serviceWorker.controller) {
          // The updatefound event implies that registration.installing is set:
          // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
          var installingWorker = registration.installing;

          installingWorker.onstatechange = function() {
            switch (installingWorker.state) {
              case 'installed':
                // At this point, the old content will have been purged and the
                // fresh content will have been added to the cache.
                // It's the perfect time to display a "New content is
                // available; please refresh." message in the page's interface.
                break;

              case 'redundant':
                throw new Error('The installing ' +
                                'service worker became redundant.');

              default:
                // Ignore
            }
          };
        }
      };
    }).catch(function(e) {
      console.error('Error during service worker registration:', e);
    });
  }

  // Your custom JavaScript goes here

   var myImage = document.querySelector('img');

   myImage.onclick = function() {
    var mySrc = myImage.getAttribute('src');
    if(mySrc === 'images/chargers2.jpg') {
      myImage.setAttribute ('src','images/chargers3.jpg');
    } else {
      myImage.setAttribute ('src','images/chargers2.jpg');
    }
   }

    var myButton = document.querySelector('button#change-user');
    var myHeading = document.querySelector('h1');
    debugger;

    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.textContent = 'Good day to you,' + myName;
    }

    if(!localStorage.getItem('name')) {
      setUserName();
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.textContent = 'Good day to you,' + storedName;
    }

    myButton.onclick = function() {
      setUserName();
    }
  })();<|endoftext|>


<commit_before>(function(module) {
  var repos = {};

  repos.all = [];

  repos.requestRepos = function(callback) {
    $.ajax({
      url: 'github.com/user/repos?per_page=10&sorted=updated',
      type: 'GET',
      // headers: {'Authorization': 'token ' + githubToken},
      success: function(data) {
        repos.all = data;
        callback(data);
      }
    // }).done(callback);
  });

  repos.with = function(attr) {
    return repos.all.filter(function(repo) {
      return repo[attr];
    });
  };

  module.repos = repos;
})(window);
<commit_msg>syntax errors<commit_after>(function(module) {
  var repos = {};

  repos.all = [];

  repos.requestRepos = function(callback) {
    $.ajax({
      url: 'github.com/user/repos?per_page=10&sorted=updated',
      type: 'GET',
      // headers: {'Authorization': 'token ' + githubToken},
      success: function(data) {
        repos.all = data;
        callback(data);
      }
    });
  };

  repos.with = function(attr) {
    return repos.all.filter(function(repo) {
      return repo[attr];
    });
  };

  module.repos = repos;
})(window);
<|endoftext|>