Home > Enterprise >  How can I stop a player spamming the a correct letter from increasing the score
How can I stop a player spamming the a correct letter from increasing the score

Time:04-10

New to programming and still learning the basics. I am trying to prevent a player from spamming a single correct letter to increase the score. I put a cap on the score that it cannot increase past 5, as it is a 5 letter word but I am currently stumped possibly due to a lack of coffee.

Here is my code in a fiddle, thanks in advance. https://jsfiddle.net/JerryCoin/ngtbrd1c/1/

function checkLetter() {
document.onkeyup = function (event) {
    guess = event.key.toLowerCase();
    let found = false;
    for (i = 0; i < word.length; i  ) {
        if (guess === word[i] && score < 5) {
            correctLetters[i] = guess;
            scoreBox.innerHTML = score  = 1;
            letterSpace();
            return;
        }
    }
    if (found) return;
    if (wrongLetters.indexOf(guess) < 0 && attempts > 0) {
        wrongLetters.push(guess);
        document.getElementById("used-letters-box").innerHTML = wrongLetters.join('');
        attemptsBox.innerHTML = attempts -= 1;
    }
    if (attempts == 0 && score < 5) {
        loseGame();
    }
};

}

CodePudding user response:

The answer to this depends on a couple of things: From what I'm able to discern, correctLetters seems to be an array of equal length to the number of characters in word. Assuming your correctLetters Array was instantiated with correctLetters = Array(word.length), then your array elements are undefined until correctLetters[i] is set by the checkLetter function. As such, you could add another check in your for loop if (guess === word[i] && score < 5 && correctLetters[i] === undefined) //If the letter hasn't been guessed, it will be undefined

Another strategy you could use would be to have a new array of correctGuesses, and push in correct guesses like you do with incorrect guesses

const correctGuesses = [];
...
if (guess === word[i] && score < 5 && !correctGuesses.includes(guess) {
    correctLetters[i] = guess;
    correctGuesses.push(guess);
    scoreBox.innerHTML = score  = 1;
    letterSpace();
    return;
}
  • Related