Hangman Error

0

I'm developing a fork game using JavaScript and I can not solve two problems

  • Whenever I hit the first letter and print the word on the screen, it prints only after I hit the second letter and does not store the letter

  • The error vector is giving null

  • What am I missing?

    var paises = ["brasil", "canada", "espanha", "irlanda", "egito", "russia", "china", "australia", "argelia", "mexico"]
    var letra = /\[a-z]/
    var chute = document.getElementById("resposta")
    var tentativas = document.getElementById("tentativas");
    tentativas.innerText = 6;
    var rand = paises[Math.floor(Math.random() * paises.length)]; //Método para selecionar um elemento string de um array
    var resposta = []
    var erro = []
    erro.length = 6;
    var correta = []
    
    function valida() {
      var chute2 = chute.value; //Atribuir o valor do objeto chute
      chute2.toString(); //convertendo o objeto para string
      var tentativas2 = parseInt(tentativas.innerText);
      if (chute2 != "") {
        forca(tentativas2, chute2, rand, erro);
      } else {
        alert("Digite uma letra");
      }
    
    }
    
    function forca(tentativas2, chute2, rand) {
      var palavra = rand;
      if (tentativas2 != 0 && comparar(palavra, chute2) == true) {
        alert("Letra correta. Tente mais uma")
        lerVetor(palavra, chute2, resposta, erro)
        espacoPalavraCorreta(resposta, correta, chute2);
        document.getElementById("resposta").value = "";
      } else if (tentativas2 != 0 && comparar(palavra, chute2) == false) {
        alert("Letra errada. Tente mais uma")
        tentativas2--
        tentativas.innerText = tentativas2
        lerVetor(palavra, chute2, resposta)
    
        document.getElementById("resposta").value = "";
    
      } else if (resposta != palavra && tentativas2 == 0) {
        alert("Suas chances acabaram. A palavra correta é " + palavra)
        window.location.reload()
      } else {
        alert("Você venceu o jogo")
        window.location.reload()
      }
    
    
    }
    
    
    function comparar(palavra, chute2) {
      if (palavra.indexOf(chute2) != -1) {
        return true
      } else {
        return false
      }
    }
    
    
    function lerVetor(palavra, chute2, resposta, erro) {
    
      var palavraTamanho = palavra.length;
      var x;
      for (var i = 0; i < palavraTamanho; i++) {
        if (palavra[i] == chute2) {
          resposta[i] = chute2;
          //resposta[i].innerText = chute2
        } else {
          x = 0;
          erro[x] = chute2;
          x++
          break
        }
      }
    
    }
    
    
    
    function espacoPalavraCorreta(resposta, correta, chute2) {
      var tamanho = resposta.length;
    
      for (var j = 0; j < tamanho; j++) {
    
        if (resposta[j] != chute2) {
          correta[j] = document.getElementById("letras_corretas")
          correta[j].textContent = correta[j].textContent + " _ " //Comando para adicionar elementos no vetor e evitar override
        } else if (resposta[j] == chute2) {
          correta[j] = document.getElementById("letras_corretas");
          correta[j].textContent = correta[j].textContent + resposta[j]
        }
        //Próximo desafio: Entender por que o vetor erro dá nulo e como pegar a String temporária e substituir seus caracteres
      }
    
    }
    <h1>O jogo da forca mais épico de toda a história</h1>
    <p class="p">Sua Resposta: <input type="text" class="sua_resposta" id="resposta" name="resposta"></p>
    <input type="button" value="Chutar" onclick="valida()">
    <p class="p">Tentativas: <span id="tentativas"></span></p>
    <p class="p">A Resposta Correta: <span id="correta"></span></p>
    <p class="p">Letras corretas: <span id="letras_corretas"></span></p>
    <p class="p">Letras erradas: <span id="erros"></span></p>
        
    asked by anonymous 08.05.2017 / 20:18

    1 answer

    1

    You have some wrong "details" in addition to the two that you mentioned.

    For example,

    var erro = []
    erro.length = 6;
    

    It is incorrect to modify the length property of an array in Javascript, at least in your case, the only case I know that the length property is modified is when the programmer wants to remove some elements from the array, your case I do not advise, maybe that's even what is causing the error.

    Then, in the function forca :

    var palavra = rand;
    

    Note that whenever the user kicks a letter, the word that was previously obtained randomly will be replaced by another, ie the user will be kicking letters for different words at the same time! The correct would be to get that word at the time the page loads.

    Another detail is the .toString() method, notice that this method returns a string representing the object in question. That is, this method does not modify the original variable itself, so it would have to be:

    chute2 = chute2.toString();
    

    instead of:

    chute2.toString();
    

    Anyway, it was not necessary to use it here.

    There are other minimum details that can be improved but otherwise gave to understand its logic and what it intended to do.

      

    Whenever I hit the first letter and print the word on the screen, it prints only after I hit the second letter and does not store the letter

    I have not thoroughly investigated this problem but it certainly is in the espacoPalavraCorreta function, I chose to follow another path, instead of doing that way you were trying to do I did the following:

    var resposta = palavra.replace(/./g, '_').split('');
    

    this takes the previously obtained word and randomly from the array palavras and replaces all the characters with _ . The .split('') is to convert the String to an array of characters. Then

    for (let i = 0; i < palavra.length; i++) {
      if (palavra[i] == chute) {
        resposta[i] = chute;
      }
    }
    

    This is the part that tries to replace, in the correct position, the _ by the letter that the user kicked correctly.

    I hope you have understood my explanations.

    I tried to leave the code in a way that you can understand, I hope the use of fewer functions will not confuse you.

    • Removed your% of% of HTML and instead used the onclick method, I did this because using inline event handlers is considered "bad practice".
    • The addEventListener is just to ensure that the script runs after the page loads completely.

    window.addEventListener('load', function() {
      const palavras = ["brasil", "canada", "espanha", "irlanda", "egito", "russia", "china", "australia", "argelia", "mexico"];
    
      const input = document.getElementById("resposta");
      const tentativasElem = document.getElementById("tentativas");
      const respostaElem = document.getElementById("correta");
      const letrasCorretas = document.getElementById("letras_corretas");
      const letrasErradas = document.getElementById("letras_erradas");
      const botaoChutar = document.getElementById("chutar");
    
      var tentativas = 6;
      tentativasElem.innerText = tentativas;
    
      const palavra = palavras[Math.floor(Math.random() * palavras.length)];
    
      var resposta = palavra.replace(/./g, '_').split('');
      respostaElem.innerText = resposta.join('');
    
      const corretas = [];
      const erradas = [];
    
      botaoChutar.addEventListener('click', function() {
        if (tentativas > 0) {
          let chute = input.value.trim().toLowerCase();
    
          if (corretas.indexOf(chute) != -1 || erradas.indexOf(chute) != -1) {
            alert("Você já chutou essa letra. Tente uma letra diferente.");
          } else if (chute && /^[A-Z]$/i.test(chute)) {
            forca(chute);
          } else {
            alert("Digite uma letra.");
          }
        } else {
          alert("Suas tentativas se esgotaram.");
        }
      });
    
      function forca(chute) {
        if (palavra.indexOf(chute) != -1) {
          for (let i = 0; i < palavra.length; i++) {
            if (palavra[i] == chute) {
              resposta[i] = chute;
            }
          }
          respostaElem.innerText = resposta.join('');
    
          corretas.push(chute);
          letrasCorretas.innerText = corretas.join(", ");
    
          if (resposta.join('') == palavra) {
            alert("Parabéns, você venceu!");
            window.location.reload();
          } else {
            alert("Letra correta. Tente mais uma.");
            document.getElementById("resposta").value = "";
          }
        } else {
          tentativasElem.innerText = --tentativas;
    
          erradas.push(chute);
          letrasErradas.innerText = erradas.join(", ");
    
          if (!tentativas) {
            alert("Suas chances acabaram. A palavra correta era " + palavra + ".");
            window.location.reload();
          } else {
            alert("Letra errada. Tente novamente.");
            document.getElementById("resposta").value = "";
          }
        }
      }
    });
    <h1>O jogo da forca mais épico de toda a história</h1>
    <p class="p">Sua Resposta:
      <input type="text" class="sua_resposta" id="resposta" name="resposta">
    </p>
    <input type="button" value="Chutar" id="chutar">
    <p class="p">Tentativas: <span id="tentativas"></span></p>
    <p class="p">A Resposta Correta: <span id="correta"></span></p>
    <p class="p">Letras corretas: <span id="letras_corretas"></span></p>
    <p class="p">Letras erradas: <span id="letras_erradas"></span></p>
        
    09.05.2017 / 19:08