Error in Hangman Game

Asked

Viewed 127 times

0

I’m developing a hangman game using Javascript and can’t solve two problems

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

  2. The vector error keeps 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>

1 answer

1

You have some "details" wrong beyond the two you mentioned.

For example,

var erro = []
erro.length = 6;

it is incorrect to modify the property length of a Javascript array, at least in your case, the only case I know where the property length is modified when the programmer wants to remove some elements from the array, but in your case I do not advise, maybe this is 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 randomly obtained will be replaced by another, ie the user will be kicking letters to different words at the same time! The correct thing would be to get that word at the moment the page is loaded.

Another detail is the method .toString(), note 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 wasn’t necessary to use here.

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

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

I did not investigate this problem in depth but it is certainly in function espacoPalavraCorreta, I chose to go another way, instead of doing that way that 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 replace all 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 the user kicked correctly.

I hope you can understand my explanations.

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

  • I removed your onclick HTML and instead I used the method addEventListener, I did this because the use of "inline Event handlers" is considered "bad Practice".
  • The window.addEventListener('load' ... is only 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>

  • I don’t have time right now, but if you want I can add comments to the code later if you’re having trouble understanding something.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.