简体   繁体   中英

Logic of hangman game with javascript

I am trying to build a hangman game and I need help with the logic. I am in a beginners class so I want to try and build this using beginners syntax. What I am trying to figure out

2) My issue is I need to display dashes (-) that represent blank lines and they need to be the same length of the randomly chosen word. In addition, every time a letter is correctly guessed, I need to replace the dashes with the correctly chosen letter. A solution I have thought of is making an empty array and then assigning it the dash signs in a for loop that is the length of the string and then replacing the indexes of specific dashes with matched letters, but I am not sure if this will work.

var randomWords = ['rock', 'paper', 'scissors'];
var numWins = 0;
var chosenWord = randomWords[Math.floor(Math.random() * randomWords.length)];
document.onkeyup = function(event) {
    // var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
    var dashes = "";
    for (var x = 0; x < chosenWord.length; x++) {
      dashes += " - ";
      // document.getElementById("word").innerHTML = blankLines;
      // document.getElementById("word").innerHTML = ;
    }
    document.getElementById("word").innerHTML = dashes;

Trying to replace a dash with a letter in lines below. But both commented out code and non commented out codes work. That is why I am thinking of using an empty array but not sure if I can fill it with data using a foor loop

     // for (x = 0; x < chosenWord.length; x++)
     // {
     //         dashes[x] = "a";
     //         dahes.charAt(x) = 'a';
     // }
     dashes.charAt(0) = "a";
     document.getElementById("test2").innerHTML = dashes;

This one should work. In the first case (if there's a white space in the word) it will display a whitespace. In the second case, it will replace every letter of the word with a dash.

 var dashes = ""; for (i = 0; i < chosenWord.length; i++) { if (chosenWord.charAt(i) == " ") { dashes += " "; } else { dashes += "-"; } }

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