Hangman Game - 无法在正确的位置打印字符串字符

时间:2018-01-30 18:15:53

标签: javascript jquery html

我正在尝试创建一个刽子手游戏。我想通过做一些基本的游戏逻辑我已经相当远了。但它没有在字符串中的适当位置打印猜测。

例如,如果单词是'pitch'并且用户猜测't',它将在索引0处打印't'而不是它实际上的索引。现在我用charAt(x)打印,但我尝试过indexOf,但似乎也没有用。

有什么想法吗?

JS:

// creating array of random words

var words = ["evaluate", "leader", "glory", "thanks", "pit", "sign", "neighborhood", "twist", "beneficiary", "giant", "bargain", "analyst", "embark", "competition", "bench", "impress", "tick", "elegant", "wing", "spring", "rider", "romantic", "confuse", "arrange", "critic", "quiet", "raise", "paradox", "inject", "gallery"];
var randWord = words[Math.floor(Math.random() * words.length)];
var randWordLngth = randWord.length;

console.log('The random word is ' + randWord + " and the length is " + randWordLngth);

var temp = '';

// printing an empty space for each character in the word length
for(var i = 0; i < randWordLngth; i++){
    temp = temp + '___ ';
}

$('#wordBox').html(temp);


$('#subBTN').click(function(){
    // get user input
    var userInput = $('input').val();
    // clear input field after capturing data
    $('input').val('');

    // check if input matches a charater in the random word
    var wordCheck = randWord.indexOf(userInput);
    console.log(wordCheck);

    //if userInput character is in the string, print character at its position to html
    if(wordCheck >= 0) {
        $('#wordBox').html(randWord.charAt(wordCheck) + temp);
    } else {
        $('.list-group').append("<li class='list-group-item'>" + randWord.charAt(wordCheck) + "</li>");
    }

});

HTML:

<div class="container">
        <div class="row">
            <div class="col-sm-3"></div>
            <div class="col-sm-6">
                <div id="wordBox" class="row pt-5"></div>
                <div id="inputBox" class="row pt-5">
                    <div class="col-sm-2"></div>
                    <div class="col-sm-8">
                        <div class="input-group mb-3">
                            <input type="text" id="guessBox" class="form-control" placeholder="Guess a letter...ex: 'a', 'b', 'c'...">
                            <div class="input-group-append">
                              <button class="btn btn-outline-secondary" id="subBTN" type="button">Go!</button>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-2"></div>
                </div>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="row" style="border: 1px solid; height: 300px">
            <div id="wrongLtrs" class="col-sm-6" style="border: 1px solid">
                <h3 class="card-title text-center pt-3">Incorrect Guesses</h3>
                <ul class="list-group"> 
                    <!-- where the wrong guesses go as a list -->
                </ul>
            </div>
            <div class="col-sm-6"></div>
        </div>
    </div>

enter image description here

3 个答案:

答案 0 :(得分:0)

这一行总是会打印位置0处的字符+变量temp上的字符: $('#wordBox')。html(randWord.charAt(wordCheck)+ temp);

答案 1 :(得分:0)

你的问题是这一行: $('#wordBox').html(randWord.charAt(wordCheck) + temp);

它只是将#wordBox的内容更改为猜测字母,然后是临时变量,在本例中为4个空格。

你需要存储正确猜到的字母(即:在一个数组中),并在每次玩家正确猜出一个字母时使用它们重新计算临时变量。

答案 2 :(得分:0)

你有几个障碍。

  1. indexOf仅返回第一次出现的位置。你应该把它放在一个循环中。
  2. 你没有跟踪猜测时存在的单词。有两个字符串 - 一个有找到的答案,另一个有找到的答案。他们互相掩饰。例如。 randWord可能=&#34; neighb.rh..d&#34;和guessedWord =&#34; ...... o..oo。&#34;
  3. 用空白替换猜测单词上的空白点,使间距正确:例如: guessedWord.replace(&#34;。&#34;,&#34; ___&#34;);
  4. 这只是一组建议 - 还有其他方法,但我认为这将产生最简单的决心,因为你已经解决了。

    以下是您完成所有这些更改后代码的示例...

    (注意 - 这是未经测试的 - 只是为了让你进入球场)

    // creating array of random words
    
    var words = ["evaluate", "leader", "glory", "thanks", "pit", "sign", "neighborhood", "twist", "beneficiary", "giant", "bargain", "analyst", "embark", "competition", "bench", "impress", "tick", "elegant", "wing", "spring", "rider", "romantic", "confuse", "arrange", "critic", "quiet", "raise", "paradox", "inject", "gallery"];
    var randWord = words[Math.floor(Math.random() * words.length)];
    var guessedWord = randWord.replace(/./, "."); /** Create a variable string of periods to denote an unguessed letter. **/
    var randWordLngth = randWord.length;
    
    console.log('The random word is ' + randWord + " and the length is " + randWordLngth);
    
    var temp = '';
    
    $('#wordBox').html(temp);
    
    
    $('#subBTN').click(function(){
        // get user input
        var userInput = $('input').val();
        // clear input field after capturing data
        $('input').val('');
    
        // check if input matches a charater in the random word
        var wordCheck = randWord.indexOf(userInput);
        while (wordCheck >= 0) {
            console.log(wordCheck);
            guessedWord = guessedWord.substr(0, wordCheck) + userInput + guessedWord.substr(wordCheck + 1);
            randWord = randWord.substr(0, wordCheck) + "." + randWord.substr(wordCheck + 1);
            wordCheck = randWord.indexOf(userInput);
        }
    
        //if userInput character is in the string, print character at its position to html
        if(wordCheck >= 0) {
            // printing an empty space for each character in the word length
            $('#wordBox').html(guessedWord.replace(".", "___ ").replace(/([a-z])/i, "_$1_ "));
        } else {
            $('.list-group').append("<li class='list-group-item'>" + randWord.charAt(wordCheck) + "</li>");
        }
    }