简体   繁体   中英

Hangman game. 2 arrays. One need to update accordingly to the other one

Im building a javascript hangman game and I'm somewhat stuck at this one problem.

Lets say the word to guess is "dog". I have created an array of this word: ["d", "o", "g"]; A hint (in for of a paragraph) in the browser is displayed with an "-" for each of the letters in the chosen word. In this scenario the hint would display --- .

If the user is to guess a letter correctly I want the hint to display for example d-- if the letter d is correctly guessed.

I have created a array out of the hint and to use the dog example the array looks like this: ["-", "-", "-"];

What I'm stuck with is how to update this second array with the corresponding letter at the right place. The array should look something like: ["d", "-", "-"]; and then I can array.join() and display the resulting string as a new hint.

Something like the below should work well. Since both your answerArray and displayArray are the same length you can simply loop through the answerArray , check for any matches, and push said matches to the appropriate position in displayArray .

var answerArray = ["d", "o", "g"],
    displayArray = ["-", "-", "-"],
    length = answerArray.length,
    i;

var currentGuess = prompt("Please enter a letter: ");

for (i = 0; i < length; i++) {

    if(currentGuess === answerArray[i]) {

        displayArray[i] = currentGuess;

    }

}

You have two arrays:

var word = ["d", "o", "g"];
var guessedWord = ["-", "-", "-"];

When the letter is correct you can do:

var idx = word.indexOf("d");
guessedWord[idx] = word[idx];

The arrays should be the same length, so you can just naively assign the value(s).

Really basic example.

http://jsbin.com/qoteqakona/1/edit?js,console

var word = 'hello'.split('');

var blanks = word.map(function (e) {
  return '-';
});

function guess(l) {
  word.forEach(function (e, i) {
    if (e === l) blanks[i] = word[i];
  });

  return blanks;
}

console.log(guess('l'));
console.log(guess('h'));
console.log(guess('i'));

In the .forEach() callback, e is the value of the current element, and i is the value of the current index.

Extra documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM