JavaScript Array not resetting in my game

I have made a quite simple hangman game but I have run into some issues.

If I lose a few games in a row, my array that contains wrong letters will be filled up even though I empty it when I start a new game.

I have been debugging for a long time now and I can not locate the root of the problem.

JS:

var gameContainer = $('#game');

function newGame() {
    console.log('----- new game -----')
    gameContainer.html('');

    var rightLetters = [];
    var wrongLetters = [];
    var rightLettersContainer;
    var wrongLettersContainer;
    var imageState;
    var imageStateCount = 0;

    function wordSelector() {
        var words = [
            'havestol',
            'tastatur',
            'skærm',
            'teleskop',
            'postkasse',
            'flaske',
            'handske',
            'skoletaske',
            'diskotek',
            'skraldespand',
            'djævel',
            'sjippetov',
            'blæksprutte',
            'baghjul',
            'lommeregner',
            'isvaffel',
            'leopard',
            'underbukser',
            'tørklæde',
            'hævekort'
        ];
        return words[Math.round(Math.random() * words.length - 1)];
    }

    var word = wordSelector();

    (function () {
        rightLettersContainer = $('<div id="right-letters"></div>');
        wrongLettersContainer = $('<div id="wrong-letters"></div>');
        imageState = $('<div id="image-states" class="image-state-0"></div>');
        gameContainer.append(rightLettersContainer);
        gameContainer.append(wrongLettersContainer);
        gameContainer.append(imageState);
        for (var i = 0; i < word.length; i++) {
            rightLettersContainer.append('<span>_</span>\n')
        }
    })();

    function letterValidator(letter) {
        var exists = false;
        for (var i = 0; i < word.length; i++) {
            if (letter == word[i]) {
                exists = true;
                rightLetters[i] = letter;
                rightLettersContainer.find('span').eq(i).text(letter)
            }
        }
        if (!exists) {
            wrongLetters.push(letter);
            wrongLettersContainer.append('<span>' + letter + '</span>')
        }
    }

    function gameState() {
        if (wrongLetters.length < 8) {
            imageStateCount++;
            imageState.removeClass('image-state-' + (imageStateCount - 1));
            imageState.addClass('image-state-' + imageStateCount);
        } else {
            newGame()

        }
        if (rightLetters.join('') == word) {
            newGame()
        }
    }

    $(document).keypress(function (e) {
        var pressedKey = String.fromCharCode(e.which);
        letterValidator(pressedKey);
        gameState();

        console.log(rightLetters)
        console.log(wrongLetters)
    })
}

function loadMenu(state) {
    gameContainer.html('');

    var menu = $('<div id="menu"></div>')
    var winMessage = $('<h1>you won!</h1>');
    var loseMessage = $('<h1>you lost!</h1>');
    var button = $('<a target='_blank' href="#" id="new-game">New Game</a>')

    gameContainer.append(menu);
    if (state == 'won') {
        menu.append(winMessage);
    } else if (state == 'lost') {
        menu.append(loseMessage);
    }
    menu.append(button);

    button.on('click', function () {
        newGame();
        return false;
    })
}
loadMenu();

JSFiddle I have included a jsFiddle of the game, and you can see the array getting filled up in the log.

If you can find where the problem is it would be much appriciated, thanks in advance.

Answer:1

I guess you're binding an event each time to the document, so it runs the function all those times!

Line 83, Unbind the function with:

$(document).unbind().keypress(function (e) {

Anyway, I'd develop the structure a little better.

Answer:2

The problem is that you are repeatedly re-attaching the event. Move your event handler creation outside of the newgame function.

Answer:3

Excuse me (I can not write good English!) i want to when change combobox selected item, this item (selected item) hide in other combobox and when change again selected hide item show again in other ...

Excuse me (I can not write good English!) i want to when change combobox selected item, this item (selected item) hide in other combobox and when change again selected hide item show again in other ...

TreeView creation: function CreateNotificationTree(userId) { debugger; var data = new kendo.data.HierarchicalDataSource({ transport: { read: { url: "../api/...

TreeView creation: function CreateNotificationTree(userId) { debugger; var data = new kendo.data.HierarchicalDataSource({ transport: { read: { url: "../api/...

I created a small api to generate test data on the fly. Each call creates a fresh user and returns the created data. To load the data I use the package request: var flow = protractor.promise....

I created a small api to generate test data on the fly. Each call creates a fresh user and returns the created data. To load the data I use the package request: var flow = protractor.promise....

I want to display a jQuery UI tabs inside a Dialog but it shows up Directory Listing of my asp.net app for no reason. It also changes the css of my page. What's going on here? Javascript: $("#...

I want to display a jQuery UI tabs inside a Dialog but it shows up Directory Listing of my asp.net app for no reason. It also changes the css of my page. What's going on here? Javascript: $("#...