user3648699
user3648699

Reputation: 23

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 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.

Upvotes: 2

Views: 64

Answers (3)

Giancarlo PSK
Giancarlo PSK

Reputation: 231

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.

Upvotes: 3

user1932079
user1932079

Reputation:

What Niet said is true, but it is also a problem of scope. You define the variables inside the function (scoping them to the function).

    var rightLetters = [];
    var wrongLetters = [];
    function newGame() {
      console.log('----- new game -----')
      gameContainer.html('');
      rightLetters = [];

An adjustment like that gives you the scope you need for how you have designed things. The event handler must also be addressed.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

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

Upvotes: 1

Related Questions