I cannot increment my variable without resetting the code

Asked

Viewed 55 times

0

I’m doing a Javascript guessing game where the user has three attempts to guess a random number between 1 and 10, only during the test, whenever I miss the first attempt, I increment the trial variable, but the code finishes running. What am I missing ?

Follows 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>

1 answer

1

I tried to change as few things as possible in your code, first I removed the form, I find it unnecessary in this case, I put the variable tentativa out of the function and increment it as the user misses the number, whenever the user hits or finishes his attempts, da o alert respective and Zera the number of attempts, any doubt can comment, I hope it helps you.

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>

Browser other questions tagged

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