简体   繁体   English

用javascript实现刽子手游戏的逻辑

[英]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. 2)我的问题是我需要显示代表空行的破折号(-),并且它们需要与随机选择的单词长度相同。 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.我想到的一个解决方案是创建一个空数组,然后在 for 循环中为它分配破折号,这是字符串的长度,然后用匹配的字母替换特定破折号的索引,但我不确定这是否有效.

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这就是为什么我正在考虑使用一个空数组,但不确定是否可以使用 foo 循环用数据填充它

     // 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 += "-"; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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