I can not increment my variable without resetting the code

0

I'm doing a guessing game in JavaScript where the user has three attempts to guess a random number between 1 and 10, but during the test, whenever I fail the first try, I increment the tentative variable, but the code finishes rolling. What am I missing?

Follow the code

var chute = document.getElementById("chute")
var numero
var tentativa

function aleatorio() {

  numero = parseInt(1 + Math.random() * 10)
  var chute2 = parseInt(chute.value)
  tentativa = 0;

  if (chute2 != numero || tentativa != 2) {
    alert("Você errou! Tente de novo")
    document.getElementById("adivinha_form").reset();
  } else if (chute2 != numero && tentativa == 2) {
    alert("Suas chances acabaram! O número correto é " + numero)
  } else if (chute2 == numero) {
    alert("Parabéns! Você acertou")
  }

}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Adivinhador</title>
</head>

<body>
  <h1>Adivinhador</h1>
  <form name="adivinha" id="adivinha_form" action="#">
    <p>
      Seu chute: <br>
      <input type="text" id="chute" name="chute">
    </p>

    <button onclick="aleatorio()" reset="true">Arriscar</button>
  </form>
  <script type="text/javascript" src="adivinhacao.js"></script>
</body>

</html>
    
asked by anonymous 20.04.2017 / 20:43

1 answer

1

I tried to change the least possible things in your code, first I removed the form , I think it's unnecessary in that case, I put the variable tentativa out of the function and increment it as the user goes wrong, whenever user hit or end their attempts, give alert and zero the number of attempts, any questions can comment, I hope it helps.

var tentativa = 0;

function aleatorio() {
  var numero = parseInt(1 + Math.random() * 10);
  var chute2 = parseInt(document.getElementById("chute").value);
  if (chute2 != numero && tentativa != 2) {
    alert("Você errou! Tente de novo");
    tentativa = tentativa + 1;
  } else if (chute2 != numero && tentativa == 2) {
    alert("Suas chances acabaram! O número correto é " + numero);
    tentativa = 0;
  } else if (chute2 == numero) {
    alert("Parabéns! Você acertou");
    tentativa = 0;
  }
  console.clear();
  console.log("Número:" + numero);
  console.log("Chute:" + chute2);
  console.log("Tentativas:" + tentativa);
  document.getElementById("chute").value = "";
  document.getElementById("chute").focus();

}
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Adivinhador</title>
</head>

<body>
  <h1>Adivinhador</h1>
  <p>
    Seu chute: <br>
    <input type="text" id="chute" name="chute">
  </p>
  <button onclick="aleatorio()">Arriscar</button>
  <script type="text/javascript" src="adivinhacao.js"></script>
</body>

</html>
    
20.04.2017 / 20:59